2013-02-09 63 views
5

我尝试了一些问题与此代码:管通话和同步

#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并且进程结束,但由于某种原因它会等待父进程执行。你如何解释这个?也许我错过了一些东西。

(编辑)

+2

你为什么期望读取返回0?你没有在任何地方设置非阻塞I/O。 – Mat 2013-02-09 12:39:16

+1

...即使对于非阻塞I/O也不是0。 – 2013-02-09 12:40:17

+0

在读取过程中是否被阻塞? – 2013-02-09 12:43:45

回答

5

既然你没有使用pipe2O_NONBLOCKread被默认阻止。因此它会等待数据写入管道。

+0

当条件为false时,(fd [0],message,SIZE)> 0'? – 2013-02-09 12:53:26

+0

当管道在另一端关闭时,它变成错误;如果你还没有写任何东西,读者会假设你可能想写一些东西。 IOW管道充当隐式同步。 – loreb 2013-02-09 13:31:44

+2

管道一点也不隐含。这是一个非常明确的同步机制。可能是最常见的。也许也是最简单的。 – 2013-02-09 13:33:40