Roh*_*anC 5 c unix linux signals process
所以我试图在子进程中为SIGTSTP信号实现一个信号处理程序.
基本上我想要实现的是:
我使用命令运行它:./ testsig sleep 10
到目前为止这是我的代码:
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<string.h>
volatile sig_atomic_t last_proc_stopped;
volatile sig_atomic_t parent_proc_id;
void handle_stp(int signum)
{
if(getpid()==parent_proc_id)
{
kill(parent_proc_id,SIGCONT);
signal(SIGTSTP,handle_stp);
}
else
{
last_proc_stopped=getpid();
kill(parent_proc_id,SIGCONT);
}
}
void main(int argc, char *argv[])
{
int childid=0,status;
signal(SIGTSTP,SIG_IGN);
parent_proc_id=getpid();
childid=fork();
if(childid>=0)
{
if(childid==0)//child
{
signal(SIGTSTP,handle_stp);
strcpy(argv[0],argv[1]);
strcpy(argv[1],argv[2]);
argv[2]=NULL;
printf("Passing %s %s %s\n",argv[0],argv[1],argv[2]);
execvp(argv[0],argv);
}
else
{
wait(&status);
printf("Last Proc Stopped:%d\n",last_proc_stopped);
}
}
else
{
printf("fork failed\n");
}
}
Run Code Online (Sandbox Code Playgroud)
目前,似乎ctrl + Z有某种效果(但绝对不是我想要的!)
当我在执行睡眠的子项中间点击ctrl + Z时,光标继续闪烁(在我的情况下为10)秒,但控件没有到达父进程.
如果没有按ctrl + Z,控制将按预期返回到父级.
我究竟做错了什么?
我也看到了这个答案,但我真的无法理解它:
你有两个进程:
\n\n忽略该信号的父级,
设置处理程序的子进程,然后执行另一个进程 - 这将从内存中清除信号处理程序的代码(执行的程序将加载到调用进程的位置),因此也将清除信号设置。因此,您的信号处理函数将永远不会被调用。是否可以在 \xe2\x80\x9cexec\xe2\x80\x9d 之后发出信号处理程序生存?
你可以做什么来实现你的目标?
\n\n家长应忽略该信号,
孩子应该保留默认的信号处理(这会阻止它),
父进程应该用来waitpid()查看子进程是否退出或停止,并采取相应的行动(这涉及实际杀死已停止的子进程)。