如何在Linux中运行命令并检测C语言是否成功?

Sug*_*uge 4 c linux

我用下面的代码用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)

Ing*_*rdt 8

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)

在这里描述我使用的宏


Car*_*rum 5

pclose(3)文档:

pclose()函数等待关联的进程终止; 它返回命令的退出状态,如返回wait4(2).