绘制以下程序的进程树

时间:2013-11-28 17:55:36

标签: c operating-system fork

我必须为这段代码绘制进程树:

int main ()
{
    int i;
    for(i = 0; i < 3; i++)
        if(fork() > 0) 
            fork();
    return 0;
}

1 个答案:

答案 0 :(得分:4)

尝试pstree

int main ()
{
    pid_t father = getpid();
    int syncpipe[4];
    pipe(syncpipe);
    pipe(syncpipe + 2);

    int i;
    for(i = 0; i < 3; i++)
        if(fork() > 0) 
            fork();

    close(syncpipe[3]);
    if (getpid() == father) {
        // wait for all children to spawn
        read(syncpipe[2], &i, 1);
        char mypid[16];
        sprintf(mypid, "%d", father);
        char * args[] = {"pstree", "-p", mypid, NULL};
        execvp(*args, args);
    } else {
        close(syncpipe[1]);
        read(syncpipe[0], &i, 1);
        // father will close all open file descriptors on exit
        // then this will return with EOF
    }

    return 0;
}

打印出来:

pstree(581223)─┬─a.out(581224)─┬─a.out(581226)─┬─a.out(581243)
               │               │               └─a.out(581247)
               │               ├─a.out(581228)─┬─a.out(581242)
               │               │               └─a.out(581248)
               │               ├─a.out(581231)
               │               └─a.out(581236)
               ├─a.out(581225)─┬─a.out(581227)─┬─a.out(581246)
               │               │               └─a.out(581249)
               │               ├─a.out(581232)─┬─a.out(581238)
               │               │               └─a.out(581244)
               │               ├─a.out(581235)
               │               └─a.out(581241)
               ├─a.out(581229)─┬─a.out(581233)
               │               └─a.out(581239)
               ├─a.out(581230)─┬─a.out(581237)
               │               └─a.out(581245)
               ├─a.out(581234)
               └─a.out(581240)