C++ 在Linux中,如何在父进程死亡后将子进程留在前台?

C++ 在Linux中,如何在父进程死亡后将子进程留在前台?,c++,c,linux,shell,C++,C,Linux,Shell,假设我有一个Linux程序,它创建了一个子进程,然后死了,子进程继续。当我启动这个程序时,shell会在父程序退出后立即显示提示。我应该如何更改我的程序,以便shell将孩子留在前台 int main(int argc, char *argv[]) { switch (fork()) { case -1: perror("fork"); return 1; case 0: // child sleep(seconds

假设我有一个Linux程序,它创建了一个子进程,然后死了,子进程继续。当我启动这个程序时,shell会在父程序退出后立即显示提示。我应该如何更改我的程序,以便shell将孩子留在前台

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会话的外观:

$ ./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

$
我应该如何更改我的程序,以便shell将孩子留在程序中 前景

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会随着程序的执行而更改前台进程组-启动程序时,前台进程组会设置为程序的进程组,在父进程终止后,shell会将前台进程组设置回自己的组。
在父程序终止后,父程序中的父程序无法使shell将子程序留在前台。父进程对前台进程组所做的每一项更改都会在父进程退出后立即由shell撤消。

更重要的是,虽然子进程可以加入shell的进程组,从而在父进程终止后成为前台进程组的成员,但这并不能实现您实际想要的(与您要求的相反)-shell仍然会在父进程退出后立即发出输入提示,因为它只等待父代,而不等待子代。

Slava,不能重复这一点-问题恰恰相反,如何不创建守护进程:)@Slava,就像我说的-正好相反。守护进程不是前台进程。我没有自相矛盾。shell创建一个进程来运行程序,该进程是shell的子进程。然后程序调用
fork
来创建一个新进程,该进程是程序的子进程,是shell的孙子进程。进程组是无关的。进程只能等待它自己的子进程。Unix不提供任何方法让进程等待孙子退出,孙子也无法成为子进程。为什么需要客户端等待父进程?你想通过这样做实现什么?知道了这一点,我们或许能够提出更好的方法。