C system() how to send the output to an array??

Hi, im in need if wisdom here guys...

How could I store the output of commands like ping integrally directly into a array??? I'll be using system() to run the commands but how can I send the output to an array??? cuz I need to store it so that I can later copy the array's content to a buffer that will then be sent via sockets.

With system(), you can't. It only returns the exit status of the process it ran, but not any of it's output on stdout or stderr. Take a loop at popen/pclose if you want to capture the output.

system(3) does a fork and exec, to put it simply. You might want to look at popen(3), which returns a FILE pointer that allows you to read output from or write input to the command that you're executing.

Edit: Aaaand I just noticed that pludi has suggested exactly the same thing.

Yeah i got it to work with popen the following way

  FILE *in;
  extern FILE *popen();
  char buff[512];
  char newline[100];
  char nstat[512];
  
  strcpy(newline, "\r\n");  



  if (!(in = popen("netstat -n", "r"))) {
    exit(1);
  }
 
  
  while (fgets(buff, sizeof(buff), in)) {
    strcat(nstat, buff);
    }

  strcat(nstat, newline); 
 

  pclose(in);

Works fine on Gentoo but crashed to "segmentation fault" on Ubuntu and I foresee it do the same on MAC OS X due to memory protection... I dumped the core and ran it through gdb now I know its in the strcat() function so my understanding of it is that is that after buff is wrote once to nstat then nstat is then made into read only so when newline tries to be appended to nstat it can't then fails to segmentation fault right? How can I get around this? anyone??

From the man page of strcat (emphasis added)

So as soon as you read more that 512 bytes from the process (which, with netstat will happen almost guaranteed) you'll start trying to write into unreserved space. This space might already be claimed by another process, and so the system intervenes.

One approach might be to allocate a large enough part of memory at the beginning.
A better approach would be to allocate a bit of memory using malloc(), and expanding that if needed using realloc().

Thanks Pludi, attention error... I noticed the memory allocated for the command i was trying to run was way not enough... Another part of the problem I was getting was with the buffer size I had allocated for my socket's buffer.

Thanks again Pludi I appreciate :slight_smile: