开发者

How to execute shell command in C?

开发者 https://www.devze.com 2023-03-05 03:13 出处:网络
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

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);
}


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消