cam*_*ino 5 c linux jobs process
在关于孤立进程组的 GNU libc手册中,它提到:
“process groups that continue running even after the session leader
has terminated are marked as orphaned process groups.
When a process group becomes an orphan, its processes are sent a SIGHUP
signal. Ordinarily, this causes the processes to terminate. However,
if a program ignores this signal or establishes a handler for it
(see Signal Handling), it can continue running as in the orphan process
group even after its controlling process terminates; but it still
cannot access the terminal any more. ”
Run Code Online (Sandbox Code Playgroud)
我编写了一个测试程序,但当进程组成为一个孤儿时,它的进程没有收到SIGHUP信号.我想知道为什么?
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static void
sig_hup(int signo) //**never get called ???**
{
printf("SIGHUP received, pid = %ld\n", (long)getpid());
}
static void
pr_ids(char *name)
{
printf("%s: pid = %ld, ppid = %ld, pgrp = %ld, tpgrp = %ld\n",
name, (long)getpid(), (long)getppid(), (long)getpgrp(),
(long)tcgetpgrp(STDIN_FILENO));
fflush(stdout);
}
int
main(void)
{
char c;
pid_t pid;
pr_ids("parent");
pid = fork();
if (pid > 0) { // parent
sleep(5);
exit(0); // parent exit;
} else {
pr_ids("child");
setsid(); //create new session, and "child" becomes the session leader
pid = fork();
if(pid>0) {
sleep(20);
exit(0); // "child" exit
// so the process group become an orphan process group
}
else{
pr_ids("grandson");
signal(SIGHUP, sig_hup); // establish signal handler
sleep(60); // now becoming orphan process group
printf("end\n");
}
}
exit(0);
}
Run Code Online (Sandbox Code Playgroud)
该文档部分专门讨论了一个进程的控制终端丢失,该进程通常由于调制解调器挂断或虚拟等效物(结束 ssh 会话等)而丢失一个\xe2\x80\x94。(我认为文档中的措辞可以在这里改进)。当你使用setsid()这里时,你就放弃了对控制终端的访问setsid(),因此从那里开始不会丢失控制终端。
你可以用open()一个 tty 设备(比如 pty 从设备)来获得一个控制终端(注意你可能还需要做一些额外的操作\xe2\x80\x94FreeBSD需要一个TIOCSCTTYioctl),然后再次失去它,然后你应该得到SIGHUP信号。