2015-04-26 26 views
0

我想了解管道和C中的使用fork下面是调用fork()然后代码的例子:空调管读/写优先

  • 子进程:读取pipe并打印内容到控制台。
  • 父流程:写入pipe“hello world”。

    int main(void) 
    { 
    pid_t pid; 
    int mypipe[2]; 
    
    /* Create the pipe. */ 
    if (pipe(mypipe)) 
    { 
        fprintf(stderr, "Pipe failed.\n"); 
        return EXIT_FAILURE; 
    } 
    /* Create the child process. */ 
    pid = fork(); 
    if (pid == (pid_t)0) 
    { 
        /* This is the child process. 
        Close other end first. */ 
        close(mypipe[1]); 
        read_from_pipe(mypipe[0]);//read pipe and print the result to console 
        return EXIT_SUCCESS; 
    } 
    else if (pid < (pid_t)0) 
    { 
        /* The fork failed. */ 
        fprintf(stderr, "Fork failed.\n"); 
        return EXIT_FAILURE; 
    } 
    else 
    { 
        /* This is the parent process. 
        Close other end first. */ 
        close(mypipe[0]); 
        write_to_pipe(mypipe[1]);//write "hello world" to the pipe 
        return EXIT_SUCCESS; 
    } 
    } 
    

我的理解是,我们使用pipes,这被视为文件,这样子进程和父进程可以通信。 (这是否正确?)现在,由于父母和孩子都在使用管道,孩子会读空pipe吗?或者将pipe设为“Hello world”?为什么?我的猜测是它是随机的,因为子进程和父进程同时运行。这是真的 ?

回答

2

根据man 7 pipe,“如果进程尝试从空管道读取数据,则读取(2)将阻塞,直到数据可用”。

因此,如果read发生在write之前,它将一直等到write完成。

相反,如果read发生在write之后,很明显它会返回消息。

而这些情况中的至少一个必须是真实的,因为,仍然根据man 7 pipe“POSIX.1-2001说,写(2)小于PIPE_BUF字节s必须是原子的”,和PIPE_BUF通常是大足以胜过“Hello World”。

所以read将返回“Hello world”。

+0

好的如果'fork'被调用时'pipe'不是空的? – dimitris93

+0

然后,读取将返回(最多取决于缓冲区大小)管道中的内容,并且不会等待更多内容。 – Ekleog

+0

你怎么知道'read'会在'write'之前发生。父进程和子进程同时执行正确?那么,读取结果是不是随机的? – dimitris93