UNIX/Linuxの部屋 関数:pipe

TOP UNIX/Linuxの部屋 UNIX/Linuxコマンド一覧 用語集 新版 由来/読み方辞書 環境変数マニュアル Cシェル変数 システム設定ファイル システムコール・ライブラリ ネットワークプログラミングの基礎知識 クラウドサービス徹底比較・徹底解説




関数 pipe パイプを作成 このエントリーをはてなブックマークに追加

pipe システムコールを実行すると、新しい2つのファイルディスクリプタが作成される。
int pipes[2];
pipe(pipes);
として、pipes[1] に対して出力すると、その出力内容が pipes[0] に送られる。pipes[0]、pipes[1] はそれぞれファイルディスクリプタなので、読み書きするには低水準入出力関数である read・write を使う。
int pipes[2];
char buf[256];

pipe(pipes);
write(pipes[1],"hoge\n",strlen("hoge\n"));
read(pipes[0],buf,sizeof(buf));

printf("buf=%s",buf);
pipes[1] に書き込んだ hoge\n という文字列が pipes[0] から読み込めていることがわかるだろう。

ただし、同じプロセス内でデータのやりとりをしたところで、何のメリットもない。標準入力・標準出力のつなぎ変えを行うときに pipe を使う。

#include <unistd.h>
int pipes[2];
if ( pipe(pipes) < 0 ){
エラー
}
if ( fork() == 0 ){ // 子プロセス
dup2(pipes[0],0);
close(pipes[1]);
execl("/bin/cat","cat","-n",NULL);
exit(0);
} else { // 親プロセス
FILE *fin,*fout;
char buf[256];
int status;

close(pipes[0]);
fout = fdopen(pipes[1],"w");
fin = fopen("sample.dat","r");

while (1){
if ( fgets(buf,sizeof(buf),fin) == 0 ){
break;
}
fprintf(fout,"%s",buf);
}
fclose(fin);
fclose(fout);

wait(&status);
if ( WIFEXITED(status) ){
printf(" status=%d", WEXITSTATUS(status));
} else if ( WIFSIGNALED(status) ){
printf(" signal=%d", WTERMSIG(status));
}
}