我正在用这段代码试验一些问题:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 30
#define Error_(x) { perror(x); exit(1); }
int main(int argc, char *argv[]) {
char message[SIZE];
int pid, status, ret, fd[2];
ret = pipe(fd);
if(ret == -1) Error_("Pipe creation");
if((pid = fork()) == -1) Error_("Fork error");
if(pid == 0){ //child process: reader (child wants to receive data from the parent)
close(fd[1]); //reader closes unused ch.
while( read(fd[0], message, SIZE) > 0 )
printf("Message: %s", message);
close(fd[0]);
}
else{//parent: writer (reads from STDIN, sends data to the child)
close(fd[0]);
puts("Tipe some text ('quit to exit')");
do{
fgets(message, SIZE, stdin);
write(fd[1], message, SIZE);
}while(strcmp(message, "quit\n") != 0);
close(fd[1]);
wait(&status);
}
}
代码工作正常,但我无法解释为什么!父进程和子进程之间没有明确的同步。如果子进程在父进程之前执行,read 必须返回 0 并且进程结束,但由于某种原因它等待父进程执行。你怎么解释这个?也许我错过了一些东西。
(已编辑)