title: How to execute shell command in C?
body: <p>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?</p>
  
  <p>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?</p>
  
  <pre><code>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);
  }
  </code></pre>