[英]Child process cannot read from terminal after it's parent exit
#include <stdio.h>
#include <unistd.h>
int main() {
int pid = -1;
char buf[10] = {0};
pid = fork();
if (pid == -1) {
perror("fork");
}
if (pid == 0) {//child
printf("[child]sleeping\n");
sleep(2);//sleep to wait parent exit;
write(1, "[child]nihao\n", 13);
if (read(0, buf, 1) == -1) {
printf("[child]ops, read error\n");
}
_exit(0);
} else {
printf("[parent]exit\n");
//if (waitpid(pid, NULL, 0) < 0) {
// perror("waitpid error\n");
//}
_exit(9);
}
}
該程序將輸出:
Jason at Jason-ubuntu in ~/c/more
○ ./fd-on-close
[parent]exit
[child]sleeping
Jason at Jason-ubuntu in ~/c/more
○ [child]nihao
[child]ops, read error
╰─○ ls -la /proc/9423/fd/
total 0
dr-x------ 2 sunan sunan 0 Oct 30 19:57 .
dr-xr-xr-x 9 sunan sunan 0 Oct 30 19:57 ..
lrwx------ 1 sunan sunan 64 Oct 30 19:57 0 -> /dev/pts/33
lrwx------ 1 sunan sunan 64 Oct 30 19:57 1 -> /dev/pts/33
lrwx------ 1 sunan sunan 64 Oct 30 19:57 2 -> /dev/pts/33
有一個線程問同樣的問題,但是我想知道更多有關該線程的細節,例如如何強制孩子控制終端,如何查看該線程中提到的進度組信息以及誰來控制終端等
提前致謝!
父進程是控制終端。 子進程不控制終端。 因此,父進程死亡,子進程進入后台。 init接受該子進程並將其添加到該子進程中。 因此,只有孩子不能控制終端。
如果您想這樣做,則可以使用tcsetpgrp函數來執行此操作,以使孩子擁有控制終端。
如果父母去世,session_leader將接受終端控制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.