如何在自己的流程组中启动流程? [英] How to start a process in its own process group?
问题描述
我想在其自己的进程组中启动一个进程(或者,一旦启动,则更改其组),并且:
I would like to start a process in its own process group (or, alternatively, change its group once started) and:
- 让该组中的进程从终端响应
Ctrl
+C
- 获取进程组的ID,以便我可以通过
kill
命令终止该组中的所有进程.
- have the processes in the group respond to
Ctrl
+C
from the terminal - get the id of the process group so that I can terminate all the processes in the group via the
kill
command.
注意:我尝试了setsid prog [args]
,但是进程没有从终端响应Ctrl + C,也无法获得新的进程组ID.
Note: I tried setsid prog [args]
but the processes do not respond to Ctrl+C from the terminal nor I could get the new process group id.
我还尝试通过Perl的setpgrp($pid, $pid)
和POSIX::setpgid($pid, $pid)
更改进程组,但无济于事.
I also tried to change the process group via Perl's setpgrp($pid, $pid)
and POSIX::setpgid($pid, $pid)
, to no avail.
更大的问题:
我有一个进程(单线程;我们称它为多产"进程P
),该进程同步启动一个子进程(一个接一个;当前一个子进程终止时,它启动一个新的进程).从终端,我希望能够杀死P
及其下面的进程树.为此,我可以简单地安排杀死P
组中的进程.但是,默认行为是P
在其父进程的组中.这意味着,如果我杀死P
组中的所有进程,则P
的父级将被杀死,除非我将P
及其树放在自己的组中.
I have a process (single-threaded; let's call it the "prolific" process P
) that starts many child processes synchronously (one after another; it starts a new one when the previous child process terminates). From the terminal, I want to be able to kill P
and the tree of processes below it. To do that, I could simply arrange to kill the processes in P
's group. However, the default behavior is that P
is in the group of its parent process. That means that P
's parent will be killed if I kill all the processes in P
's group, unless I have P
and its tree be in their own group.
我的意图是杀死P
及其下面的树,而不是P
的父级.另外,我无法修改P
的代码本身.
My intention is to kill P
and the tree below it, but not P
's parent. Also, I cannot modify P
's code itself.
推荐答案
在自己的进程组中启动进程"是什么意思? Shell在自己的进程组中启动进程,这就是它进行工作控制的方式(通过在前台有一个进程组,在后台启动的每个管道都有几个进程组).
What do you mean "start a process in its own process group"? The shell launches processes in their own process groups, that's how it does job control (by having a process group for processes in the foreground, and several process groups for every pipeline launched on the background).
要查看shell为每个管道启动一个新的进程组,可以执行以下操作:
To see that the shell launches a new process group for every pipeline, you can do this:
ps fax -o pid,pgid,cmd | less
它将显示如下内容:
11816 11816 | \_ /bin/bash
4759 4759 | \_ ps fax -o pid,pgid,cmd
4760 4759 | \_ less
请注意,shell为管道创建了一个新的进程组,并且管道中的每个进程都共享该进程组.
Note that the shell has created a new process group for the pipeline, and every process in the pipeline shares the process group.
我想我知道你在做什么.您正在从Perl调用system
.显然,sh -c
不会创建新的进程组,因为它是一个没有作业控制的外壳.
I think I know what you are getting at. You are calling system
from Perl. Apparently, sh -c
doesn't create new process groups, since it's a shell without job control.
我要做的是先fork
,然后在孩子身上:
What I would do would be to fork
, then on the child:
setpgrp;
system("ps fax -o pid,pgid,cmd");
和wait
在父级上.
这篇关于如何在自己的流程组中启动流程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!