如何在C中执行shell命令

如何在C中执行shell命令

本文介绍了如何在C中执行shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中执行shell命令时遇到问题.我想在C中执行shell命令,然后捕获shell命令的输出并进一步处理输出.我使用以下代码执行功能.但是,问题在于,当shell命令不会返回任何输出时,fgets()返回的是垃圾信息吗?

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?

通过一个示例来说明,如果/etc/version包含','分隔值,则shell返回输出,而fgets返回shell命令返回的值,但是/etc/version不包含任何','分隔时值,shell不返回任何值,而fgets返回垃圾信息.是否有解决此问题的方法,或者是否有其他解决方案可以在C中执行shell命令并捕获shell命令输出?

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

推荐答案

您需要检查fgets的返回值.您正在测试的指针永远不会为NULL,因为Fgets不会更改其参数.

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
}

这篇关于如何在C中执行shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:42