How to execute shell command in C?

I'm having trouble executing shell commands in C. I want to run a shell command in C, then grab the shell command output and process the output further. To execute the functions, I used the following code. But the problem is when the shell command will not return any output, fgets () returns information about unwillingness?

To explain the example, if / etc / version contains "," separated values, shell returns the result, and fgets returns the value returned by the shell command, but when / etc / version does not match any "," separated values, shell does not return any value, and fgets returns information about unwanted information. Is there any workaround for this problem or is there an alternative solution to execute a shell command in C and output the shell shell command?

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);
}
+3
source share
1 answer

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

if ( fgets (line, 256, fp) == NULL ) {
    // read failed
}
+2
source

All Articles