c - 进程子创建新会话
问题描述
我正在尝试编写一个创建子进程的程序。子进程创建一个新会话。此外,必须验证子进程已成为组的领导者,并且它没有控制终端。
它总是显示我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!
这是你需要的吗?
推荐阅读
- cypress - 赛普拉斯无法断言新窗口 URL
- php - 为“排序依据”组合两列
- latex - 使用 eqnarray 在乳胶中更改方程对齐
- html - 边距底部未应用于某些图像
- python - 如何使字符串中的单个单词具有某种颜色
- flutter - 在颤动中停止在 DraggableScrollableSheet 中滚动
- amazon-web-services - 亚马逊sqs fifo队列中的飞行模式下如何有超过10条具有相同组ID的消息?
- amazon-s3 - Apache flink 以 S3 作为源,S3 作为接收器
- reactjs - 如何在不使用节点的情况下运行反应应用程序?
- eclipse - Eclipse Kotlin 插件未编译 Kotlin 类