簡體   English   中英

調試時為什么生成的程序退出代碼會發生變化?

[英]Why does spawned program exit code change when debugging?

我有一個C ++程序,我用來測試另一個程序不會崩潰。 父代碼(我們稱之為'parentProg')看起來像這樣:

int run(const char * command)
{
  ...

  int retCode = system(command);
  printf("Code is %d\n",retCode);
  if(retCode == 134) //128 + SIGABORT
  {
    // Record error conditions
    ...
  }
}

命令變量包含正在測試的程序(我們稱之為'childProg')。 使用以前的Linux發行版,此代碼按預期工作。 如果a.out崩潰或命中一個斷言,它將返回134並且錯誤處理代碼將運行。 但是,在我升級到更新的Linux發行版后,情況就不再如此了。 相反,當使用GDB或nemiver作為衍生程序運行時,我看到返回代碼為6。 奇怪的是,如果我單獨運行子程序或使用DDD,它將恢復到134。

對於以下測試,我將childProg修改為僅以下代碼:

#include <assert.h>

int main(int argc, char * argv[])
{
  assert(0);
  return 0;
}

childProg本身

[user@localhost multi]$ ./childProg 
childProg: temp.cpp:5: int main(int, char **): Assertion `0' failed.
Abort
[user@localhost multi]$ echo $?
134

parentProg產生childProg

[user@localhost multi]$ ./parentProg 1 o
Running 1 times
childProg: temp.cpp:5: int main(int, char **): Assertion `0' failed.
Code is 6
Done 0
[user@localhost multi]$ 

使用GDB

(gdb) run
Starting program: parentProg 1 o
Running 1 times
Detaching after fork from child process 3311.
childProg: temp.cpp:5: int main(int, char **): Assertion `0' failed.
Code is 6
Done 0
[Inferior 1 (process 3295) exited normally]
(gdb) 

有了DDD

(gdb) run 1 o
Starting program: parentProg 1 o
Running 1 times
Detaching after fork from child process 3336.
childProg: temp.cpp:5: int main(int, char **): Assertion `0' failed.
Code is 134
Done 0
[Inferior 1 (process 3319) exited normally]
(gdb) 

這按預期工作

[me@localhost multi]$ /bin/sh -c ./childProg
childProg: temp.cpp:5: int main(int, char **): Assertion `0' failed.
Abort
[me@localhost multi]$ echo $?
134

這可能會發生什么? 除了檢查退出代碼之外,還有更好的方法來檢查崩潰/段錯誤/斷言嗎?

<sys / wait.h>頭文件包含用於分析返回碼的宏。

要檢查退出的原因,您可以執行以下操作:

#include <stdio.h>
#include <sys/wait.h>

...

void run(const char *command)
{
    int retcode = system(command);

    if (WIFEXITED(retcode))
    {
        int status = WEXITSTATUS(retcode);
        if (status)
        {
            printf("Exited normally with FAILURE status of %d!\n", status);
        }
        else
        {
            printf("Exited normally with SUCCESS(0) status!\n");
        }
    }
    else if (WIFSIGNALED(retcode))
    {
        int signal = WTERMSIG(retcode);
        printf("Abnormal termination - program crashed or was aborted with signal %d\n", signal);
    }

}

有關這些宏的說明,請參閱“man waitpid”。

(134 = 6 | __WCOREFLAG)

man 2 wait

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM