简体   繁体   中英

How to pipe stdin to a file using pipe and fork system calls

I'm trying to pipe the stdin to a file using pipes.
The way I'm seeing it, is I need to make stdin be the write end of the pipe.
For code this is what I have so far:

int main(int argc, char** argv) {

    int fd[2];
    pipe(fd);
    fd_set in;
    FD_ZERO(&in);
    FD_SET(fd[0], &in);
    if(fork() == 0){
        close(fd[0]);
        dup2(fd[1], 0);
        return 1;
    }
    else{
        close(fd[1]);
        select(fd[1] + 1, &in, NULL, NULL, NULL);
        if(FD_ISSET(fd[0], &in)){
            char buff[1024];
            while(read(fd[0], &buff, sizeof(buff)) != 0){
                write(1, buff, strlen(buff));
            }
        }

    }
}  

The select statement does fire, but when I read from fd[0], there is nothing there.
Is there something that I'm missing?

Just use freopen() on stdin. That should do the trick.

dup2(fd[1], 0); doesn't do what you need it to do. After the call, when something writes into your process's STDIN, it's not going to go into the pipe fd[1] . It just makes file descriptor 0 refer to the pipe within your process . Nothing ever writes into the pipe, so there's nothing to read.

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