假设我有一个 Linux 程序,它创建一个子进程然后死掉,子进程继续。当我启动这个程序时,shell 在父级退出后立即显示提示。我应该如何更改我的程序,以便 shell 将 child 留在前台?
int main(int argc, char *argv[])
{
switch (fork())
{
case -1:
perror("fork");
return 1;
case 0: // child
sleep(seconds(5));
printf("%07u %s: Process group ID = %d\n", getpid(), currTime("%T").c_str(), getpgrp());
printf("%07u %s: Foreground process group ID = %d\n", getpid(), currTime("%T").c_str(), tcgetpgrp(STDIN_FILENO));
break;
default: // parent
printf("%07u %s: Process group ID = %d\n", getpid(), currTime("%T").c_str(), getpgrp());
printf("%07u %s: Foreground process group ID = %d\n", getpid(), currTime("%T").c_str(), tcgetpgrp(STDIN_FILENO));
break;
}
return 0;
}
如果我启动上面的命令,shell session 如下所示:
$ ./test
0007016 22:57.665929: Process group ID = 7016
0007016 22:57.666362: Foreground process group ID = 7016
$ 0007017 23:02.666229: Process group ID = 7016
0007017 23:02.666703: Foreground process group ID = 27254
我想要的东西:
$ ./test
0007016 22:57.665929: Process group ID = 7016
0007016 22:57.666362: Foreground process group ID = 7016
0007017 23:02.666229: Process group ID = 7016
0007017 23:02.666703: Foreground process group ID = 7016
$
最佳答案
How should I change my program so that shell leaves the child in foreground?
在前台 意味着属于控制终端上的前台进程组。现在,shell 会随着程序的执行而更改前台进程组 - 启动程序时,前台进程组设置为程序的进程组,在父进程终止后,shell 将前台进程组设置回自己的进程组组。
在您的程序中,父级无法执行任何操作来使 shell 在父级终止后将子级留在前台。父进程对前台进程组所做的每项更改都会在父进程退出后立即被 shell 撤消。
更重要的是,虽然子进程可以加入 shell 的进程组,从而在父进程终止后成为前台进程组的成员,但这不会实现您真正想要的(与您要求的相反)-shell 仍然会在父级退出后立即发出输入提示,因为它显然只等待父级,而不是子级。
关于c++ - 在 Linux 中,如何在父进程死后将子进程留在前台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188469/