|
导航:[首页]->[linux]->[Linux 进程组]
我们经常需要对某些进程集合进行统一控制,典型的场景如:
具体我们可以让这些进程放到一个进程组里面,然后向这个进程组发送消息。一种办法是使用kill函数。 也可以使用killpg函数 为了获得pgid,可以使用getpgrp函数,它返回当前进程的进程组ID。你也可以使用getpgid函数,它根据特定的PID来获取它的进程组ID。 默认情况下,子进程和父进程属于相同的进程组ID,为了修改子进程的进程组ID,必须在fork之后,exec之前重新重置进程组ID。可以使用setpgrp将当前进程重置,它相当于setpgid(0, 0)。 If the calling process is not already a session leader, setpgrp() sets the process group ID of the calling process to the process ID of the calling process. If setpgrp() creates a new session, then the new session has no controlling terminal. The setpgrp() function has no effect when the calling process is a session leader. 为了让子进程自动退出,我们在创建任意子进程前先重置进程组id,然后捕获退出信号(SIGINT,SIGTERM等),收到信号后向当前整个进程组发送退出消息。 为了关闭一个shell脚本进程,我们在fork之后,exec之前重置进程组ID,当需要杀进程时,向fork的进程ID所在的进程组发送退出消息。 |