C 背景-前景信号终端
我必须编写一个shell,如果命令被signal终止,它能够“打印关于signal终止进程的消息” 范例C 背景-前景信号终端,c,shell,C,Shell,我必须编写一个shell,如果命令被signal终止,它能够“打印关于signal终止进程的消息” 范例 > sleep 5 ^C terminated by signal 2 > sleep 10 & background pid is 4422 ..... // after several lines background pid is done: exit value 0 > sleep 11 & background pid is 4442 >
> sleep 5
^C terminated by signal 2
> sleep 10 &
background pid is 4422
..... // after several lines
background pid is done: exit value 0
> sleep 11 &
background pid is 4442
> kill -15 4442
background pid is done: terminate by signal 15
但是,在我的代码中:
1) 如果我^C
在睡眠5中,它将直接从shell退出,而不是只终止睡眠进程
2) 如果我键入sleep 10&
,它将直接打印背景pid为4422:退出值0
。因此,我认为这里没有睡眠,我也不能执行kill-15
我最好的猜测是它与我的启动
功能有关(许多人建议使用此功能启动程序并等待其终止),下面是它的外观:
注意:我有一个名为runBg
的全局变量,实际上我只是为测试人员创建的,如果存在后台进程,那么我将runBg
设置为1。然而,我不知道这是不是一个好主意
int launch(char **args) {
pid_t pid;
int status;
int exitStat = 0;
pid = fork();
if (pid == 0) {
if (execvp(args[0], args) == -1) {
printf("error1"); // debugging purposes
exit(EXIT_FAILURE);
}
} else if (pid < 0) {
printf("error2"); // debugging purposes
} else {
do {
if (runBg == 0) {
waitpid(pid, &status, WUNTRACED);
} else if (runBg== 1) {
waitpid(-1, &status, WNOHANG);
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
if (runBg== 1) {
printf("Background PID: %d is done: exit value: %d", pid, exitStat);
}
if (status != 0 || WIFSIGNALED(status)) {
exitStat = 1;
}
return exitStat;
int启动(字符**args){
pid_t pid;
智力状态;
int exitStat=0;
pid=fork();
如果(pid==0){
如果(execvp(args[0],args)=-1){
printf(“error1”);//调试目的
退出(退出失败);
}
}else如果(pid<0){
printf(“error2”);//调试目的
}否则{
做{
if(runBg==0){
waitpid(pid和状态,WUNTRACED);
}如果(runBg==1){
waitpid(-1,&状态,WNOHANG);
}
}而(!WIFEXITED(status)和&!WIFSIGNALED(status));
}
if(runBg==1){
printf(“后台PID:%d已完成:退出值:%d”,PID,exitStat);
}
如果(状态!=0 | | WIFSIGNALED(状态)){
exitStat=1;
}
返回exitStat;
我试着执行了几个测试,但似乎都直接陷入了error1
第一个if条件execvp……
真的是麻烦制造者吗
sleep 15&
似乎也不起作用,因为它没有转到do-while循环之后的最后一个if语句
期待你们的帮助。如果我错过了这个帖子中的chuck信息,请告诉我。谢谢。我怀疑waitpid(pid,&status,WUNTRACED);
是你问题的一部分。试着把它缩小到一个范围。@Jason是因为我使用了WUNTRACED吗?我也怀疑,但也可能是因为我没有给出if(pid=-1)条件也一样吗?有人能给建议吗?