Perl で fork した際に、親子プロセス間で通信を行うソースコードの覚書。
#!/usr/bin/perl use Socket; use IO::Handle; # autoflushのために何千行も :-( socketpair (CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair: $!"; CHILD->autoflush(1); PARENT->autoflush(1); $pid = fork; if (!defined $pid) { die "cannot fork: $!"; } elsif ($pid) { # 自分は親なので親のソケットは不要。閉じる。 close PARENT; # 子に伝言する print CHILD "Parent Pid $$ is sending this "; # 子からの伝言を受ける chomp ($line = <CHILD>); print "Parent Pid $$ just read this: `$line' "; # 子へのソケットを閉じる close CHILD; # 子プロセスの終了を待つ waitpid $pid, 0; } else { # 自分は子なので子のソケットは不要。閉じる。 close CHILD; # 親に伝言する print PARENT "Child Pid $$ is sending this "; # 親からの伝言を受ける chomp ($line = <PARENT>); print "Child Pid $$ just read this: `$line' "; # 親へのソケットを閉じる close PARENT; # プロセスを終了する exit; }