首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >进程子进程创建新会话

进程子进程创建新会话
EN

Stack Overflow用户
提问于 2020-05-06 04:18:29
回答 1查看 129关注 0票数 4

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

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

这是我的代码:

代码语言:javascript
复制
#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;
} 
EN

回答 1

Stack Overflow用户

发布于 2020-05-06 05:15:51

问题是:

代码语言:javascript
复制
while (getppid() != 1) {
  printf("Waiting for parent to die.\n");
  sleep(1);
}

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

代码语言:javascript
复制
wait(NULL)

当我执行具有此更改的程序时,我收到以下输出:

代码语言:javascript
复制
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!

这是你需要的吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61622290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档