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);
strncpy (return_val, "N/A", 4);
char cmd[] = "if [ -f /etc/umts2100_version ]; then cut -d, -f1 -s /etc/umts2100_version ; fi";
fp = popen(cmd, "r");
if (fp != NULL)
{
fgets (line, 256, fp);
if( line != NULL)
{
strncpy(return_val, line, strnlen (line, 256));
}
pclose (fp);
}
source
share