call system()返回256

时间:2014-10-15 06:02:19

标签: c++ c solaris

我想system()在我的应用程序中打印pstack信息,但它失败了并返回256.但是我把这些代码拿到一个新的主函数,这没关系。为什么呢?

char cmd[256] ;
string pstackCmd;
struct timeval tv;
struct tm lt;(&tv, NULL);

localtime_r(&tv.tv_sec, &lt);
sprintf(cmd, "pstack `pgrep app` > pstack_%04d%02d%02d%02d%02d%02d%03d",
                            lt.tm_year+1900,
                            lt.tm_mon+1,
                            lt.tm_mday,
                            lt.tm_hour,
                            lt.tm_min,
                            lt.tm_sec,
                            (int)(tv.tv_usec/1000));
pstackCmd = string(cmd);
int retValue = system(pstackCmd.c_str());
if ( retValue != 0)
{
    printf("pstack `pgrep app`,retValue:%d",retValue);
}

2 个答案:

答案 0 :(得分:1)

而不是:

if (retValue != 0)

你需要这个:

if (retValue == -1 || WEXITSTATUS(retValue) != 0)

也就是说,首先通过查看system()是否返回-1来检查故障;如果它没有那么命令的退出状态(传统上零意味着成功)。

答案 1 :(得分:0)

这意味着出现了问题并且命令未成功执行。返回值256实际上意味着1

有关详情,请查看以下链接:

System Return Code (was: 256)

system()

If you'd like to manually inspect system's failure, you can check all possible failure modes by inspecting `$?` like this:

if ($? == -1) {
    print "failed to execute: $!\n";
}
elsif ($? & 127) {
    printf "child died with signal %d, %s coredump\n",
        ($? & 127),  ($? & 128) ? 'with' : 'without';
}
else {
    printf "child exited with value %d\n", $? >> 8;
}

$? >> 8的位移是8,基本上除以256。