理系学生日記

おまえはいつまで学生気分なのか

socketpair なんてのがあるんだな

プロセス間で通信というと,pipe システムコールを 2 つ使って,送信用と受信用ソケット作るだろ常考というのがぼくの中での固定観念としてあったんですけど,なんか socketpair なんてお洒落なものがあるということを知ったりしました.いやリアルで全然知らなかったし,うひゃーみたいな感じです!!

知ったのはモダン Perl 入門からなんだけど,とりあえず一回システムコールで試してみたくなった. ISBN:978-4-7981-1917-5:detail

作ってみたけど,なんかエラー処理だの何だのが途中でメンドくさくなったりして,動けば良いということにした.ソースはこんな感じ.

|c|

include <stdio.h>

include <sys/types.h>

include <sys/socket.h>

include <unistd.h>

include <string.h>

int main() {

char buf[512]; int sv[2]; pid_t child; const char child_msg = "hello from child"; const char parent_msg = "hello from parent";

if ( socketpair( AF_UNIX, SOCK_STREAM, 0, sv ) < 0 ) { perror( "socketpair" ); return 1; }

if ( (child = fork() ) < -1 ) { perror( "fork" ); }

if ( child ) { close( sv[1] ); write( sv[0], parent_msg, strlen( parent_msg ) ); read( sv[0], buf, sizeof( buf ) ); printf( "parent: %s\n", buf ); } else { close( sv[0] ); write( sv[1], child_msg, strlen( child_msg ) ); read( sv[1], buf, sizeof(buf) ); printf( "child: %s\n", buf ); }

return 0; } ||<

|tcsh| $ ./a.out parent: hello from child child: hello from parent ||< wait 呼ぶの忘れた.