68user's page 掲示板

Prev< No. 2988> Next  [最新発言に戻る] [過去ログ一覧]
No. 2988 # hsj 2002/12/18 (水) 14:58:58
>>2986 koko
> ・親プロセスはwaitしません。
親でSIGCHLDを拾ってwaitpid()のオプションWNOHANGで
チェックするのもダメですか?
--- snip ---
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>

void handler(int sig)
{
        int pid,status,code;

        while((pid=waitpid(-1,&status,WNOHANG))>0)
        {
                if(WIFEXITED(status))
                {
                        code = WEXITSTATUS(status);
                        printf("child process:[%d] was exited with code:[%d]\n",pid,code);
                }
        }
}

int main(int argc,char *argv[])
{
        int i,pid,code;
        char buf[16];
        struct sigaction sa;

        if(argc>1)
        {
                code = atoi(argv[1]);
                srand(code+time(0));
                sleep(rand()%10);
                return code;
        }

        memset(&sa,0,sizeof(sa));
        sa.sa_flags = SA_NOCLDSTOP;
        sa.sa_handler = handler;
        sigaction(SIGCHLD,&sa,0);

        for(i=0;i<10;i++)
        {
                if((pid=fork())<0)
                {
                        perror("fork");
                        return -1;
                }
                if(pid)
                        continue;
                sprintf(buf,"%d",i);
                if(execl("./a.out","./a.out",buf,0)<0)
                {
                        perror("execl");
                        return -2;
                }
        }
        for(;;)
                sleep(1);
        return 0; /* never reaches */
}
--- snip ---
かなり適当ですが。

Prev< No. 2988> Next  [最新発言に戻る] [過去ログ一覧]