簡體   English   中英

關閉管道,dup2,C中的文件描述符?

[英]Closing pipe, dup2, file descriptors in C?

我正在運行一個做管道的程序。 我要運行的命令是ls | 貓。

int cmd(char** w, int* pipe, int action){
... some code up here
...
int fd;
if(child_pid == 0) {
    if (pipe != 0) {

        if (action == 0){
            fd = dup2(pipe[0], STDIN_FILENO);
            close(pipe[0]);
            close(pipe[1]);
            //close(fd);
        }
        else if (action == 1){
            fd = dup2(pipe[1], STDOUT_FILENO);
            close(pipe[0]);
            close(pipe[1]);
            //close(fd);
        }


    }

    execvp(w[0], w);



    printf("Unknown command\n");
    exit(0);
  }
... some code down here

當我運行代碼時,命令ls | cat正常運行,除了cat沒有結束(即管道沒有關閉,只等在那里什么也不做)。 我認為這是因為我沒有關閉流或其他東西,但是我對C / IO並不足夠了解。 我這樣做對嗎?

運行此功能的代碼就像

int fd[2];
int p = pipe(fd);
cmd(w, fd, 1);
cmd(w, fd, 0);

編輯:您的權利,致命錯誤,我在爭論中輸錯了

thxs,看起來我只需要關閉父級中的pipe [1]

在兩次cmd調用之后,父進程還需要關閉管道的兩端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM