類似の機能について
類似した機能として、socketpair(2)
および名前なしpipe
がありますが、これらはディスクリプタと似て異なる点もあります。同じ動きをするプログラムは、それぞれ下記のとおりとなります。
なお、こちらがpipe(2)
のリファレンスとsocketpair(2)
のリファレンスになります。
#include <sys/wait.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> int main( int argc, char ** argv ) { int fd[2], j; uint64_t u; if( argc < 3 ) { fprintf( stderr, "Usage: %s <num> <num>...\n", argv[0] ); exit( EXIT_FAILURE ); } pipe( fd ); switch( fork( )) { case 0: close( fd[0] ); for( j = 2; j < argc; j ++ ) { u = strtoull( argv[j], NULL, 0 ); write( fd[1], &u, sizeof( u )); } close( fd[1] ); printf( "Child completed\n" ); exit( EXIT_SUCCESS ); default: close( fd[1] ); printf( "Parent sleep %d sec.\n", atoi( argv[1] )); sleep( atoi( argv[1] )); while( read( fd[0], &u, sizeof( uint64_t )) > 0 ) printf( "parent_read by pipe:[%lld]\n", ( unsigned long long )u ); close( fd[0] ); printf( "Parent completed\n" ); exit( EXIT_SUCCESS ); } }
#include <sys/wait.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> int main( int argc, char ** argv ) { int fd[2], j; uint64_t u; if( argc < 3 ) { fprintf( stderr, "Usage: %s <num> <num>...\n", argv[0] ); exit( EXIT_FAILURE ); } socketpair( AF_LOCAL, SOCK_STREAM, 0, fd ); switch( fork( )) { case 0: close( fd[0] ); for( j = 2; j < argc; j ++ ) { u = strtoull( argv[j], NULL, 0 ); write( fd[1], &u, sizeof( u )); } close( fd[1] ); printf( "Child completed\n" ); exit( EXIT_SUCCESS ); default: close( fd[1] ); printf( "Parent sleep %d sec.\n", atoi( argv[1] )); sleep( atoi( argv[1] )); while( read( fd[0], &u, sizeof( uint64_t )) > 0 ) printf( "parent_read by sock:[%lld]\n", ( unsigned long long )u ); close( fd[0] ); printf( "Parent completed\n" ); exit( EXIT_SUCCESS ); } }
それぞれの実行結果は下記の通りです。
# ./eventfd_sample 2 1 2 3 4 5 Child completed Parent sleep 2 sec. Parent read by eventfd:[15] ← 1~5 の合計値になる(必ずではない) # ./pipe_sample 2 1 2 3 4 5 Child completed Parent sleep 2 sec. parent_read by pipe:[1] ← 個別で読み込まれる parent_read by pipe:[2] parent_read by pipe:[3] parent_read by pipe:[4] parent_read by pipe:[5] Parent completed # ./socketpair_sample 2 1 2 3 4 5 Child completed Parent sleep 2 sec. parent_read by sock:[1] ← 個別で読み込まれる parent_read by sock:[2] parent_read by sock:[3] parent_read by sock:[4] parent_read by sock:[5] Parent completed #