【问题标题】:call system() return 256调用系统()返回 256
【发布时间】:2014-12-10 02:45:29
【问题描述】:

我想 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);
}

【问题讨论】:

标签: c++ c solaris


【解决方案1】:

而不是这个:

if (retValue != 0)

你需要这个:

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

也就是说,您首先通过查看system() 是否返回-1 来检查失败;如果没有,则命令的退出状态(传统上为零表示成功)。

【讨论】:

    【解决方案2】:

    这意味着出了点问题,命令没有成功执行。返回值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。

    【讨论】:

    • >> 8 完美运行...我有一个脚本返回 1 并在我的使用 system 运行脚本的 c 代码中不断获得 256。现在我收到了我的期望..
    猜你喜欢
    • 2013-09-30
    • 1970-01-01
    • 2012-02-11
    • 2013-03-25
    • 2016-05-23
    • 2012-10-07
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    相关资源
    最近更新 更多