我正在编写一个程序监视器作为操作系统课程的作业(虽然非常基础,比如对它的介绍)。
监视器必须做的事情之一是显示它正在监视的程序的终止代码,如果它以“自然原因”或负责终止它的信号代码结束。
现在我只是等待孩子结束执行然后捕获终止代码。这是相关的代码段:
pid_t id = -1;
switch (id = fork()) {
// Error when forking:
case -1:
error(-1, "Something went wrong when forking.");
exit(-1);
// Code for the child process:
case 0:
// Just launch the program we're asked to:
execvp(argv[2], &argv[2]);
// If reached here it wasn't possible to launch the process:
error(1, "Process could not be launched.");
exit(1);
// Code for the parent process:
default:
// Just wait for the child to finish its execution:
wait(&return_value);
}
error(2)
是一个记录器函数,只是为了在出现错误时简化代码。
取决于我必须如何显示不同陈述的过程:
Process ended: X
或
Process terminated with signal X.
其中X将是终止代码或收到的信号。我们怎么知道儿童过程是否因信号而结束?
答案 0 :(得分:5)
来自wait(2)
:
WIFSIGNALED(status)
returns true if the child process was terminated by a signal.
WTERMSIG(status)
returns the number of the signal that caused the child process to terminate.
因此,您需要检查WIFSIGNALED(return_value)
,如果确实如此,请检查WTERMSIG(return_value)
。