Bidirectional Communication with Yourself

Bidirectional Communication with Yourself

If you want, you may make low-level pipe() and fork() to stitch this together by hand. This example only talks to itself, but you could reopen the appropriate handles to STDIN and STDOUT and call other processes.

    #!/usr/bin/perl -w
    # pipe1 - bidirectional communication using two pipe pairs
    #         designed for the socketpair-challenged
    use IO::Handle;     # thousands of lines just for autoflush :-(
    pipe(PARENT_RDR, CHILD_WTR);                # XXX: failure?
    pipe(CHILD_RDR,  PARENT_WTR);               # XXX: failure?
    CHILD_WTR->autoflush(1);
    PARENT_WTR->autoflush(1);
    if ($pid = fork) {
        close PARENT_RDR; close PARENT_WTR;
        print CHILD_WTR "Parent Pid $$ is sending this\n";
        chomp($line = <CHILD_RDR>);
        print "Parent Pid $$ just read this: `$line'\n";
        close CHILD_RDR; close CHILD_WTR;
        waitpid($pid,0);
    } else {
        die "cannot fork: $!" unless defined $pid;
        close CHILD_RDR; close CHILD_WTR;
        chomp($line = <PARENT_RDR>);
        print "Child Pid $$ just read this: `$line'\n";
        print PARENT_WTR "Child Pid $$ is sending this\n";
        close PARENT_RDR; close PARENT_WTR;
        exit;
    }

But you don't actually have to make two pipe calls. If you have the socketpair() system call, it will do this all for you.

    #!/usr/bin/perl -w
    # pipe2 - bidirectional communication using socketpair
    #   "the best ones always go both ways"
    use Socket;
    use IO::Handle;     # thousands of lines just for autoflush :-(
    # We say AF_UNIX because although *_LOCAL is the
    # POSIX 1003.1g form of the constant, many machines
    # still don't have it.
    socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
                                or  die "socketpair: $!";
    CHILD->autoflush(1);
    PARENT->autoflush(1);
    if ($pid = fork) {
        close PARENT;
        print CHILD "Parent Pid $$ is sending this\n";
        chomp($line = <CHILD>);
        print "Parent Pid $$ just read this: `$line'\n";
        close CHILD;
        waitpid($pid,0);
    } else {
        die "cannot fork: $!" unless defined $pid;
        close CHILD;
        chomp($line = <PARENT>);
        print "Child Pid $$ just read this: `$line'\n";
        print PARENT "Child Pid $$ is sending this\n";
        close PARENT;
        exit;
    }
 Bidirectional Communication with Yourself