简体   繁体   中英

A puzzle between child and parent process over pipe

Currently I'm leaning how to use pipe between child process and parent process, simply parent process writes to a pipe and child would read from pipe

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#define READEND 0
#define WRITEEND 1
int
main(int argc, char *argv[]){
  int fd[2];
  pipe(fd);
  if (fork()){
     close(fd[READEND]);
     int write_number;
     for (int i = 2; i < 36; i++){
         write_number = i;
         write(fd[WRITEEND], &write_number, sizeof(write_number));
     }
     close(fd[WRITEEND]);
     wait(0);
  }else{// child process
     close(fd[WRITEEND]);
     int read_number[34];
     int len;
     int prime;
     int read_pipe = fd[READEND];
     while ((len = read(read_pipe, &read_number, sizeof(read_number))) > 0){
         printf("len : %d, %d\n", len / 4, getpid());
     }
  }
  exit(0);
}

When I run multiple times, something quite unusual happened, but I have no idea, here is the output:

~# ./a.out
len : 34, 30375
~# ./a.out
len : 34, 30383
~# ./a.out
len : 1, 30397
len : 1, 30397
len : 1, 30397
len : 31, 30397
~# ./a.out
len : 34, 30411
~# cc pipe_pipe.c
~# ./a.out
len : 33, 30454
len : 1, 30454

It seems like the child goes to the next iteration in the while loop, so that's why not only one line output, but I have closed all the write end of the pipe, it should know that I will just read once, but some runs do not output 34... So can anyone analyze that why it is this? thx

You have two processes running in parallel. When you call read , there is no guarantee that all the writes have been executed by the other process, so the read call will not be able to return all 34 integers and will probably just return whatever is in the pipe.

With a little more work, you can probably put the read end of the pipe into blocking mode, meaning that it will try to wait until all the data you requested has been read before it returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM