我用下面的代码用C在Linux中运行一个命令,我只能得到这个函数的输出,我怎么能检测是否它已成功运行?有没有代表这个的返回码?
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;
}
Run Code Online (Sandbox Code Playgroud)
pclose()返回被调用程序的退出状态(如果wait4()失败,则返回-1(参见手册页),这样你就可以检查:
#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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1344 次 |
| 最近记录: |