2016-10-02 74 views
0

我在看如何在手冊頁上使用管道(2),我不明白他們提供的源代碼中的一行。未初始化的數組傳遞到管道(2)

int 
    main(int argc, char *argv[]) 
    { 
     int pipefd[2]; //Isn't this undefined??? so pipe(pipefd) would throw an error? 
     pid_t cpid; 
     char buf; 

     if (argc != 2) { 
      fprintf(stderr, "Usage: %s <string>\n", argv[0]); 
      exit(EXIT_FAILURE); 
     } 

     if (pipe(pipefd) == -1) { 
      perror("pipe"); 
      exit(EXIT_FAILURE); 
     } 

     cpid = fork(); 
     if (cpid == -1) { 
      perror("fork"); 
      exit(EXIT_FAILURE); 
     } 

     if (cpid == 0) { /* Child reads from pipe */ 
      close(pipefd[1]);   /* Close unused write end */ 

      while (read(pipefd[0], &buf, 1) > 0) 
       write(STDOUT_FILENO, &buf, 1); 

      write(STDOUT_FILENO, "\n", 1); 
      close(pipefd[0]); 
      _exit(EXIT_SUCCESS); 

     } else {   /* Parent writes argv[1] to pipe */ 
      close(pipefd[0]);   /* Close unused read end */ 
      write(pipefd[1], argv[1], strlen(argv[1])); 
      close(pipefd[1]);   /* Reader will see EOF */ 
      wait(NULL);    /* Wait for child */ 
      exit(EXIT_SUCCESS); 
     } 
    } 

我以爲非靜態函數變量只是在內存中的任何東西?爲什麼這個源代碼工作?

+0

歡迎來到堆棧溢出 - 儘管你之前已經提出過問題。 請注意,在這裏說'謝謝'的首選方式是通過 提高投票的好問題和有用的答案(一旦你有足夠的聲譽這樣做),並接受任何 問題最有用的答案,你問(這也給你一個小小的提升,以你的聲望 )。 請參閱[關於]頁面,以及[如何在此處提問 ?]和 [當有人回答我的 問題時,我該怎麼辦? ?](http://stackoverflow.com/help/someone-answers) –

回答

3

pipefd數組在這裏作爲輸出參數,所以不需要初始化它。 pipe函數寫入它。

+0

啊我現在明白了,非常感謝! –

0

Array pipefd返回2個指向管道末端的fds。這裏,pipefd [1]指向管道的寫入結束,pipefd [0]指向管道的讀取結束。

在上面的程序:

  1. [1]在孩子不使用,因此它是封閉的pipefd。數據是由孩子從pipefd [0]讀取的。

請注意,如果管道爲空,則讀取塊,如果管道已滿,則寫入塊。

  1. pipefd [0]沒有在父級中使用,因此它被關閉。數據由父級寫入pipefd [1]。

另外請注意,作爲管是單向的,寫入到寫入端的數據(pipefd [1])管,是由內核緩衝,直到它從管的讀取端讀取(pipefd [0])。