3

I am having problems executing the shell commands in C. I want to execute a shell command in C then capture the output of shell command and process the output further. I used following code to perform the functionality. But, the issue is when the shell command won't return any output, fgets() returns junk information?

To explain with an example, if /etc/version contains ',' seperated values, shell returns the output and fgets returns the value returned by shell command, but when /etc/version doesn't contian any ',' seperated values, shell doesn't return any value and fgets returns junk information. Is there any workaround for this issue or is there any alternative solution to execute shell command in C and capture shell command output?

char return_val[256];
FILE *fp = NULL;
char line[256];
memset (return_val, 0, 256);
/* set the defalut value */
strncpy (return_val, "N/A", 4);
char cmd[] = "if [ -f /etc/umts2100_version ]; then cut -d, -f1 -s /etc/umts2100_version ; fi";

/* Open the command for reading. */
fp = popen(cmd, "r");
if (fp != NULL) 
{
    /* read the line from file */
    fgets (line, 256, fp);
    if( line != NULL)
    {
            /* copy the data */
            strncpy(return_val, line, strnlen (line, 256)); 
        }
      /* close the file */ 
    pclose (fp);
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
Ravi
  • 653
  • 3
  • 10
  • 21

1 Answers1

2

You need to examine the return value of fgets. The pointer you are testing will never be NULL, as Fgets does not change its parameters.

if ( fgets (line, 256, fp) == NULL ) {
    // read failed
}
  • Hi, I tried what you have suggested. Issue with the suggeseted solution is that if the stream has less than 255 bytes (consider it has only 2 bytes), fgets returns NULL but copies the content of 2 bytes into line. Please correct me if I am wrong.. – Ravi May 12 '11 at 12:54
  • @Ravi Are the two bytes a line? In other words do they have a \n at the end? If not, you may have to read the stream with fread or fgetc rather than fgets. –  May 12 '11 at 13:27
  • Thanks for your response. I dont think that \n is exist at the end of line. fp reaches end of the file and that is the reason, fgets() returns NULL. I think fgetc() is the better option. – Ravi May 13 '11 at 06:37