简体   繁体   中英

Create pipes after fork

Is it possible/correct to do this? If i do a write from fd1[1] of the "child" process, then make it possible to read from fd2[0] of the "father" process?

main(){
    pid_t pid;
    pid = fork();
    if(pid <0){
        return -1;
    }
    if(pid == 0){
        int fd1[2];
        int fd2[2];
        pipe(fd1);
        pipe(fd2);
        close fd1[1];
        close fd2[0];
        //writes & reads between the fd1 pipes
        //writes & reads between the fd2 pipes
    }else{
        int fd1[2];
        int fd2[2];
        pipe(fd1);
        pipe(fd2);
        close fd1[1];
        close fd2[0];
        //writes & reads between the fd1 pipes
        //writes & reads between the fd2 pipes
    }
}

No, pipes used to communicate between processes should be created before the fork() (otherwise, you have no easy way to send thru them, since the reading and the writing ends should be used by different processes).

there are dirty tricks to send a file descriptor between processes as an out of band message on socket, but I really forgot the details, which are ugly

You need to setup the pipe before forking .

int fds[2];

if (pipe(fds))
    perror("pipe");

switch(fork()) {
case -1:
    perror("fork");
    break;
case 0:
    if (close(fds[0])) /* Close read. */
        perror("close");

    /* What you write(2) to fds[1] will end up in the parent in fds[0]. */

    break;
default:
    if (close(fds[1])) /* Close write. */
        perror("close");

    /* The parent can read from fds[0]. */

    break;
}

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