我使用下面的代码在Linux中运行C命令,我只能得到这个函数的输出,如何检测它是否成功运行?是否有任何返回代码表示此?
const char * run_command(const char * command)
{
const int BUFSIZE = 1000;
FILE *fp;
char buf[BUFSIZE];
if((fp = popen(command, "r")) == NULL)
perror("popen");
while((fgets(buf, BUFSIZE, fp)) != NULL)
printf("%s",buf);
pclose(fp);
return buf;
}发布于 2013-09-03 14:39:01
pclose()返回名为(或-1 )的程序的退出状态,如果wait4()失败(),请参阅手册页),以便您可以检查:
#include <sys/types.h>
#include <sys/wait.h>
....
int status, code;
status = pclose( fp );
if( status != -1 ) {
if( WIFEXITED(status) ) { // normal exit
code = WEXITSTATUS(status);
if( code != 0 ) {
// normally indicats an error
}
} else {
// abnormal termination, e.g. process terminated by signal
}
}我使用的宏被描述为这里。
发布于 2013-09-03 14:38:52
来自pclose(3)文档:
pclose()函数等待相关进程终止;它返回命令的退出状态,正如wait4(2)返回的那样。
发布于 2013-09-03 14:39:15
pclose返回管道的出口代码。
https://stackoverflow.com/questions/18594901
复制相似问题