【发布时间】:2021-04-11 04:25:44
【问题描述】:
这看起来很简单,一个管道,父级将在管道的写入端写入管道,子级将在while循环中从管道读取,并打印读取的内容,但我的程序未能停止...
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char *argv[]){
int fd[2];
int number;
int write_number[1];
pipe(fd);
int pid;
if ((pid = fork()) >0){
close(fd[0]);
for (int i = 2; i < 36; i++){
*write_number = i;
write(fd[1], write_number, 4);
}
printf("write finished from parent process:%d\n", pid);
close(fd[1]);
}else{// child process
close(fd[1]);
while(read(fd[0], &number, 4))
printf("The number is %d from child %d\n", number, getpid());
close(fd[0]);
}
exit(0);
}
顺便说一句,这是来自 xv6 类 Unix 系统,但我认为这与在 Linux 中几乎相同,输出:
$ primes
The numbwerite finished from parent prorc eis ss:24
from $ child 4
The number is 3 from child 4
The number is 4 from child 4
The number is 5 from child 4
The number is 6 from child 4
The number is 7 from child 4
The number is 8 from child 4
The number is 9 from child 4
The number is 10 from child 4
The number is 11 from child 4
The number is 12 from child 4
The number is 13 from child 4
The number is 14 from child 4
The number is 15 from child 4
The number is 16 from child 4
The number is 17 from child 4
The number is 18 from child 4
The number is 19 from child 4
The number is 20 from child 4
The number is 21 from child 4
The number is 22 from child 4
The number is 23 from child 4
The number is 24 from child 4
The number is 25 from child 4
The number is 26 from child 4
The number is 27 from child 4
The number is 28 from child 4
The number is 29 from child 4
The number is 30 from child 4
The number is 31 from child 4
The number is 32 from child 4
The number is 33 from child 4
The number is 34 from child 4
The number is 35 from child 4
它没有停止,所以它挂起,但是我已经关闭了我应该关闭的文件描述符,所以如果没有读取任何内容,read 系统调用应该返回 0,为什么它仍然挂起,所以任何人都可以帮我一把?谢谢!
【问题讨论】:
-
你有没有试过在最后一次输出后按
Enter键?你得到你的提示了吗?然后是因为父进程退出(早在子进程之前)并且shell重新获得了控制权。然而,子进程还没有完成并继续写入输出。在读取循环之后添加一个额外的输出来验证(除了Enter键检查)。 -
我最初的想法是parent会一个接一个的往管道里写入一系列整数,child会一个接一个地从管道中读取,读完后我关闭相关文件描述符,当文件描述符全部关闭时,意味着文件结束,所以不需要按回车键,我只是想验证我的想法是否可行......但似乎有问题