简体   繁体   中英

Closing pipe, dup2, file descriptors in C?

I'm running a program that does piping. The command I want to run is ls | cat.

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

When I run the code, the command ls | cat runs fine except that the cat doesn't end(ie the pipe doesn't close and just waits there doing nothing). I think it's because I didn't close a stream or something, but I'm not familiar enough with C/IO to know for sure. Am I doing this right?

the code that runs this function is like

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

edit: ur right, fatalerror, i mistyped on the arguement

thxs, looks like i just needed to close pipe[1] in the parent

在两次cmd调用之后,父进程还需要关闭管道的两端。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM