Adonis K. Kakoulidis
Adonis K. Kakoulidis

Reputation: 5133

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
    }
}

Upvotes: 0

Views: 923

Answers (2)

cnicutar
cnicutar

Reputation: 182639

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;
}

Upvotes: 4

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

Upvotes: 4

Related Questions