【发布时间】:2011-08-23 22:37:20
【问题描述】:
我在 C 中执行 shell 命令时遇到问题。我想在 C 中执行 shell 命令,然后捕获 shell 命令的输出并进一步处理输出。我使用以下代码来执行该功能。但是,问题是当shell命令不返回任何输出时,fgets()返回垃圾信息?
举例说明,如果/etc/version包含','分隔值,shell返回输出,fgets返回shell命令返回的值,但是当/etc/version不包含任何','分隔时值,shell 不返回任何值, fgets 返回垃圾信息。是否有解决此问题的方法,或者是否有任何替代解决方案可以在 C 中执行 shell 命令并捕获 shell 命令输出?
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);
}
【问题讨论】: