向子进程发送 SIGINT
我正在尝试创建一个子进程,然后将 SIGINT 发送给子进程而不终止父进程。我尝试了这个:
pid=fork();
if (!pid)
{
setpgrp();
cout<<"waiting...\n";
while(1);
}
else
{
cout<<"parent";
wait(NULL);
}
但是当我点击抄送时,两个进程都被终止
I am trying to create a child process and then send SIGINT to the child without terminating the parent. I tried this:
pid=fork();
if (!pid)
{
setpgrp();
cout<<"waiting...\n";
while(1);
}
else
{
cout<<"parent";
wait(NULL);
}
but when I hit C-c both process were terminated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用CTRL-C,这会向具有相同控制终端(即在同一会话中)的所有进程发送信号。这是
setpgid
不会改变的事情,尽管我认为有一个setsid
(设置会话 ID)调用用于此目的。最简单的解决方案就是针对特定进程而不是会话。从命令行:
从 C:
其中 pid 是要将信号发送到的进程 ID。
父级可以从
fork()
的返回值中获取相关的PID。如果子进程想要自己的 PID,它可以调用getpid()
。Don't use CTRL-C, this sends a signal to all processes with the same controlling terminal (ie, in the same session). That's something that
setpgid
doesn't change though I think there's asetsid
(set session ID) call for that purpose.The easiest solution is simply to target the specific process rather than a session. From the command line:
From C:
where pid is the process ID you want to send the signal to.
The parent can get the relevant PID from the return value from
fork()
. If a child wants its own PID, it can callgetpid()
.啊哈,进程组和会话以及进程组组长和会话组组长的谜团又出现了。
您的控制/C 向一组发送了信号。您需要向单个 pid 发出信号,因此请遵循 paxdiablo 的指示或从父进程向子进程发出信号(“杀死”)。并且不要忙着等待!将 sleep(1) 放入循环中,或者更好的是,将 wait(2) 系统调用之一放入循环中。
Aha, the mystery of process groups and sessions and process group leaders and session group leaders appears again.
Your control/C sent the signal to a group. You need to signal an individual pid, so follow paxdiablo's instructions or signal ("kill") the child from the parent. And don't busy wait! Put a sleep(1) in the loop, or better yet, one of the wait(2) system calls.
您可以尝试实现一个 SIGINT 信号处理程序,如果子进程正在运行,则杀死子进程(如果没有,则关闭应用程序)。
或者,将父级的 SIGINT 处理程序设置为 SIG_IGN,将子级的 SIGINT 处理程序设置为 SIG_DFL。
You could try implementing a SIGINT signal handler which, if a child process is running, kills the child process (and if not, shuts down the application).
Alternatively, set the parent's SIGINT handler to SIG_IGN and the child's to SIG_DFL.