将退出类型作为字符串返回的函数

时间:2014-02-20 06:08:03

标签: c unix exit

我希望我的程序输出进程退出的方式,如用户提示和输入后的第二行所示。

shell> wait
shell: process has exited abnormally with signal 11: Segmentation fault.

我在printf()中使用什么功能?我想到了exit()但是返回了void。 可能是strsignal ,如果是这样,我会传递什么作为strsignal的int?谢谢!

2 个答案:

答案 0 :(得分:1)

您是正确的,它是strsignal()。请参见以下示例:https://www.cs.fsu.edu/~baker/opsys/examples/forkexec/print_child_status.c

相关部分:

  $(document).ready(function(){
     $('.collapsible').collapsible();
   });

答案 1 :(得分:-1)

您可以在以下链接http://linux.die.net/man/2/waitpid

中查看最后的代码

该计划的示范:

$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$

该计划的来源:

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

int
main(int argc, char *argv[])
{
    pid_t cpid, w;
    int status;

   cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

   if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %ld\n", (long) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));

   } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
            if (w == -1) {
                perror("waitpid");
                exit(EXIT_FAILURE);
            }

           if (WIFEXITED(status)) {
                printf("exited, status=%d\n", WEXITSTATUS(status));
            } else if (WIFSIGNALED(status)) {
                printf("killed by signal %d\n", WTERMSIG(status));
            } else if (WIFSTOPPED(status)) {
                printf("stopped by signal %d\n", WSTOPSIG(status));
            } else if (WIFCONTINUED(status)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        exit(EXIT_SUCCESS);
    }
}