作者:超级活死人 | 来源:互联网 | 2023-05-17 07:41
ImtryingtounderstandhowpipesworkinC.Myfatherprocessgeneratestheintegersfrom1to10
I'm trying to understand how pipes work in C. My father process generates the integers from 1 to 10 and writes them in a pipe. My child process has to read the pipe and print the values to screen. The father waits for child termination and exits. Easy, right? Here's my code:
我正在尝试理解管道如何在C中工作。我的父进程生成从1到10的整数并将它们写入管道。我的子进程必须读取管道并将值打印到屏幕。父亲等待终止孩子并退出。容易,对吗?这是我的代码:
#include
#include
#include
#include
#include
#include
#define WRITE 1
#define READ 0
#define N 10
int main(void)
{
pid_t pid;
int B0[2];
int num, status, i;
pipe(B0);
pid = fork();
if (pid > 0){
/*P0*/
close(B0[READ]);
for (i=1; i<=N; i++){
num = i;
write(B0[WRITE],&num,sizeof(num));
printf("P0: written %d\n", num);
}
close(B0[WRITE]);
wait(&status);
exit(EXIT_SUCCESS);
}
else if (pid == 0){
/*P1*/
close(B0[WRITE]);
do{
if (read(B0[READ],&num,sizeof(num)) != -1)
printf("P1: read %d from pipe B0\n", num);
else
printf("read: %s\n", strerror(errno));
} while(read(B0[READ],&num,sizeof(num)) != 0);
exit(EXIT_SUCCESS);
}
}
I don't understand why as output I receive the following:
我不明白为什么作为输出我收到以下内容:
P0: written 1
P0: written 2
P0: written 3
P0: written 4
P0: written 5
P0: written 6
P0: written 7
P0: written 8
P0: written 9
P0: written 10
P1: read 1 from pipe B0
P1: read 3 from pipe B0
P1: read 5 from pipe B0
P1: read 7 from pipe B0
P1: read 9 from pipe B0
P1: read 10 from pipe B0
Regardless of the integer sequence I'm writing in the pipe, my read() skips every 2nd value. I've tried to sleep(1) while writing the value to the pipe, but the result is the same. I am missing something, but I don't get what. What's happening?
无论我在管道中写入的整数序列如何,我的read()都会跳过每个第2个值。我在将值写入管道时尝试睡眠(1),但结果是一样的。我错过了什么,但我没有得到什么。发生了什么?
2 个解决方案