c报告哪个信号终止了孩子 [英] c reporting which signal terminated a child
问题描述
我一直在广泛地研究shell,现在我正尝试升级此代码以报告子级是否已被信号(SIGINT除外)终止.如果圆括号中发生了一次(类似于bash),我还试图报告核心转储".
I've been working on a shell pretty extensively, and now I'm trying to upgrade this code to report when a child has been terminated by a signal (other than SIGINT). I'm also trying to report a "core dump" if one happened in parenthesis (similar to 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处理这种事情,但是我需要能够打印出一个特定的数字.像这样:
I'm not really sure how to proceed with this. This is my first time working this extensively with the fork() command and my knowledge of the parent-child relationship is pretty shoddy, to tell the truth. I've searched for answers and the closest I've gotten is that SIGCHLD handles this sort of thing, but I need to be able to print out a specific number. something like:
printf(子级终止(%d)\ n",15 +信号);
编辑*
我在代码中加上了////////
edit*
I put what I think to be the correct implementation of what I want into the code, surrounded by ////////
推荐答案
You collect the status of the child with your chosen variant of wait()
or waitpid()
— or on BSD wait3()
or wait4()
if you like — and then analyze the status.
POSIX提供:
-
WIFEXITED(status)
—如果程序在控制下退出,则返回true. -
WEXITSTATUS(status)
—返回退出状态(0..255). -
WIFSIGNALED(status)
—如果程序由于信号而退出,则返回true. -
WTERMSIG(status)
—返回终止信号.
WIFEXITED(status)
— returns true if the program exited under control.WEXITSTATUS(status)
— returns the exit status (0..255).WIFSIGNALED(status)
— returns true if the program exited because of a signal.WTERMSIG(status)
— returns the terminating signal.
WIFSTOPPED(状态)
—如果孩子被信号阻止了.
WIFSTOPPED(status)
— if the child was stopped by a signal.
POSIX没有定义,但是许多基于Unix的实现提供:
POSIX does not define, but many Unix-based implementations provide:
-
WCOREDUMP(status)
—如果转储内核,则返回true.
WCOREDUMP(status)
— returns true if a core was dumped.
这篇关于c报告哪个信号终止了孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!