[英]Killing a child process from a signal handler
I'm writing a simple shell, and I have to fork a child process an external program using execv. 我正在编写一个简单的shell,我必须使用execv为子进程分叉一个外部程序。 I have to send the signal TSTP(Cntl+Z) to the signal handler, and then kill the currently running child process.
我必须将信号TSTP(Cntl + Z)发送到信号处理程序,然后终止当前正在运行的子进程。 My problem is I can't find a way to pass the Child pid into the signal handler.
我的问题是我找不到将Child pid传递给信号处理程序的方法。 If i do a getpid() in the handler, it just returns the parent pid.
如果我在处理程序中执行getpid(),它只返回父pid。 I also tried setting the child pid as getpid() inside the child process, and having that variable as a global variable, but that also didn't work.
我还尝试将子pid设置为子进程内的getpid(),并将该变量作为全局变量,但这也不起作用。 Here is some of the code I have so far.
这是我到目前为止的一些代码。
void handler(int);
//in main
if (!built_in_cmd(myArgc,myArgs)) {
pid_t pid;
char *x = myArgs[0];
if((pid=fork())<0)
printf("Parent: fork() process failed");
else {
if (pid == 0) {
y=getpid();
printf("Parent: My child has been spawned. %d %d\n",y,getppid());
execv(x, myArgs);
exit(0);
}
else {
signal(SIGTSTP,handler);
wait(0);
printf("Parent: My child has terminated.\n");
}
}
}
return;
//outside main
void handler(int signo){
kill(idk,SIGKILL);
}
Signals are asynchronous in nature, there's no way to pass any extra state to them except through global variables. 信号本质上是异步的,除了通过全局变量之外,没有办法将任何额外的状态传递给它们。 Assuming that you only ever have one thread waiting for a child, it's safe to use a global, but otherwise there's no multithread-safe way of doing so:
假设你只有一个线程在等待一个孩子,那么使用全局是安全的,但是否则没有多线程安全的方法:
// At global scope
pid_t child_pid = (pid_t)-1;
...
void myfunc()
{
pid_t pid;
if((pid = fork()) < 0)
...
else if(pid == 0)
...
else
{
child_pid = pid;
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.