system执行linux命令通过返回值判断是否成功

来源:互联网 发布:高性能javascript 2015 编辑:程序博客网 时间:2024/04/25 23:15

static intRunCommand(string& result,const string& command,bool erroutput =false)

{

   if(erroutput)

      command +=  "2>&1 ";

   FILE* fp = popen((command + redirector).c_str(),"r");

   if (fp == NULL)

   {

      result = string("run commandfailed:") + strerror(errno) +",command:" + command;

      return -1;

   }

   stringstream ss;

   char linebuf[512];

   while (fgets(linebuf,sizeof(linebuf), fp) != NULL)

   {

      if (ss.tellp() < (4<< 10))

      {

          ss << linebuf;

      }

   }

   int ret = pclose(fp);

   if (ret == -1 ||!WIFEXITED(ret))

   {

      result = string("run commandfailed:") + strerror(errno) +",command:" + command;

      return -1;

   }

   int exitcode =WEXITSTATUS(ret);

   result = ss.str();

   return exitcode;

}

 

WIFEXITED(status)如果子进程正常结束则为非0值。

WEXITSTATUS(status)取得子进程exit()返回的结束代码,一般会先用WIFEXITED 来判断是否正常结束才能使用此宏。

WIFSIGNALED(status)如果子进程是因为信号而结束则此宏值为真。

WTERMSIG(status)取得子进程因信号而中止的信号代码,一般会先用WIFSIGNALED 来判断后才使用此宏。

WIFSTOPPED(status)如果子进程处于暂停执行情况则此宏值为真。一般只有使用WUNTRACED 时才会有此情况。

WSTOPSIG(status)取得引发子进程暂停的信号代码,一般会先用WIFSTOPPED 来判断后才使用此宏。

0 0
原创粉丝点击