2015-04-26 25 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