我一直在广泛地研究shell,现在我正在尝试升级此代码,以便在子信号被信号(SIGINT除外)终止时报告。 如果在括号中发生一个(类似于bash),我也会尝试报告“核心转储”。
...
if(test == -1){
cpid = fork();
if(cpid < 0){
//Fork wasn't successful
perror("fork");
free(argList);
return -1;
}
if(cpid == 0){
//We are the child!
close(pipefd[0]);
dup2(pipefd[1], 1);
execvp(args[0], args);
//execvp returned, wasn't successful
perror("exec");
fclose(stdin);
exit(127);
}
close(pipefd[1]);
//Have the parent wait for child to complete, if flags allow
if(strcmp(flags, "NOWAIT") != 0){
if(wait (&status) < 0){
//Wait wasn't successful
perror("wait");
}
else{
////////////////////////////////////////////////////////
//report if a child has been terminated by a signal other than SIGINT
if((WIFSTOPPED(status) && (WSTOPSIG(status) != SIGINT))){
printf("child terminated by signal [%d]\n", WSTOPSIG(status));
if(WCOREDUMP(status)){
printf("core dumped\n");
}
}
//////////////////////////////////////////////////////////
free(argList);
//since no child is running, return 0
return 0;
}
}
else{
//if a child is running, return the child's pid
return cpid;
}
}
...
我不确定如何继续这个。这是我第一次使用fork()命令进行广泛的工作,而且我对亲子关系的了解非常粗制,说实话。我已经搜索过答案了,我得到的最接近的是SIGCHLD处理这类事情,但我需要能够打印出一个特定的数字。类似的东西:
printf("child terminated (%d)\n", 15 + signal);
编辑*
我把我认为正确实现我想要的东西放在代码中,包围在////////
答案 0 :(得分:5)
您使用所选的wait()
或waitpid()
变体收集孩子的状态,或者根据您的喜好收集BSD wait3()
或wait4()
- 然后分析状态
POSIX提供:
WIFEXITED(status)
- 如果程序退出控制,则返回true。WEXITSTATUS(status)
- 返回退出状态(0..255)。WIFSIGNALED(status)
- 如果程序因信号而退出,则返回true。 WTERMSIG(status)
- 返回终止信号。
WIFSTOPPED(status)
- 如果孩子被信号拦住了。
WSTOPSIG(status)
- 阻止孩子的信号。WIFCONTINUED(status)
- 如果孩子因停止信号而继续。POSIX没有定义,但许多基于Unix的实现提供:
WCOREDUMP(status)
- 如果转储核心,则返回true。