forkを用いたプロセスのフォーキングについて。
// gcc -std=c99
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
// 生成する子プロセス数
#define CHILD_MAX (5)
//
// ミリ秒単位のsleep
//
int msleep( int milliseconds )
{
struct timespec t;
t.tv_sec = milliseconds / 1000;
t.tv_nsec = ( milliseconds % 1000 ) * 1000000;
return nanosleep( &t, NULL );
}
//
// 親プロセスの処理
//
void parent_main()
{
printf( "parent process %d started\n", getpid() );
// 250ミリ秒間停止
msleep( 250 );
}
//
// 子プロセスの処理
//
void child_main()
{
printf( "child process %d started\n", getpid() );
// 000ミリ秒間停止
msleep( 3000 );
}
//
// 親プロセス
//
int main( void )
{
for ( int count = 0; count < CHILD_MAX; count++ )
{
// 子プロセスを生成する
pid_t pid = fork();
if ( 0 == pid )
{
// 子プロセスの処理を開始する
child_main();
_exit( 0 );
}
else if ( -1 == pid )
{
printf( "fork failed\n" );
return 1;
}
}
// 親プロセスの処理を開始する
parent_main();
// すべての子プロセスの終了を待機する
for ( int count = 0; count < CHILD_MAX; )
{
int status;
pid_t pid;
pid = waitpid( -1, &status, WNOHANG );
if( 0 < pid )
{
printf( "child process %d exited\n", pid );
count++;
continue;
}
else if ( -1 == pid )
{
break;
}
// 500ミリ秒おきに子プロセスの状態を監視する
msleep( 500 );
}
printf( "all processes are finished\n" );
return 0;
}
実行例。
child process 7729 started child process 7730 started child process 7731 started child process 7732 started child process 7733 started parent process 7728 started child process 7729 exited child process 7730 exited child process 7731 exited child process 7732 exited child process 7733 exited all processes are finished