【问题标题】:Process child creating a new session进程子创建新会话
【发布时间】:2020-05-05 20:18:28
【问题描述】:

我正在尝试编写一个创建子进程的程序。子进程创建一个新会话。另外,必须验证子进程已经成为组的leader,并且没有控制终端。

它总是显示waiting for parent to die,进入了一个无限循环。我需要改变什么,而不是那样显示?

这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {
    pid_t pid;

    if ((pid = fork()) < 0) {
        perror("fork error");
        return -1;
    } else
    if (pid == 0) {
        // Wait for the parent to die.
        while (getppid() != 1) {
            printf("Waiting for parent to die.\n");
            sleep(1);
        }

        pid = setsid();

        printf("pid, pgid and \"sid\" should be the same:\n");
        printf("pid: %d pgid: %d sid: %d\n", getpid(), getpgrp(), getsid(0));

        if ((open("/dev/tty", O_RDWR)) < 0) {
            printf("Child has no controlling terminal!\n");
        } else {
            printf("Child has a controlling terminal!\n");
        }

    } else {
        if ((open("/dev/tty", O_RDWR)) < 0) {
            printf("Parent has no controlling terminal!\n");
        } else {
            printf("Parent still has a controlling terminal!\n");
        }
        _exit(0);
    }
    return 0;
} 

【问题讨论】:

  • 我假设您的原始父进程从不将任何内容打印到屏幕上。
  • 尽管我使用的是 Mac,但我完全按照键入的方式编译了您的代码,并且运行良好。不知道该告诉你什么。

标签: c linux process child-process


【解决方案1】:

问题是:

while (getppid() != 1) {
  printf("Waiting for parent to die.\n");
  sleep(1);
}

当然返回一个不同于 1 的值。 为了等待父进程的死亡,你可以使用wait(NULL),这样你就可以改变我写的块:

wait(NULL)

当我执行这个更改的程序时,我会收到这个输出:

Parent still has a controlling terminal!
pid, pgid and "sid" should be the same:
pid: 2581 pgid: 2581 sid: 2581
Child has no controlling terminal!

这是你需要的吗?

【讨论】:

  • 谢谢,但没有。 wait用于读取孩子的情况,但是我的孩子没有其他孩子,所以wait也不做任何事情。另一方面,如果我等待父母完成控制终端,那么孩子可能会收到等待信号。而在setsid之后,我必须等待
  • 也许您可以通过管道(或其他 IPC 机制)将父进程的 pid 传递给子进程,并使用 waitpid(parent_pid) 等待父进程的终止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2015-04-26
  • 1970-01-01
  • 2018-03-05
  • 2011-01-19
  • 1970-01-01
相关资源
最近更新 更多