c - 进程子创建新 session

标签 c linux process child-process

我正在尝试编写一个创建子进程的程序。子进程创建一个新 session 。此外,必须验证子进程已成为组的领导者并且它没有控制终端。

它总是显示我 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;
} 

最佳答案

问题在于:

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!

这是你需要的吗?

关于c - 进程子创建新 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61622290/

相关文章:

linux - 无与伦比的'。设置别名时出错

python - 在python中为迭代任务创建n个进程

filtering - 使用 Fiddler 进行进程过滤

c++ - 在 C 中循环遍历十六进制变量

c - 为什么操作系统的某些部分必须用汇编编写?

linux - 从文本文件中获取值并在 UNIX 环境中进行计算

linux - 作为一名学生程序员为什么我应该使用linux

database - 您如何处理多个开发人员和数据库更改?

c - C语言图形用户界面

c++ - 栈的动态