回 帖 发 新 帖 刷新版面

主题:请教有关fork()函数的执行流程????

一段小程序如下:

int main(int argc, char **argv)
{
    int val, stat;
    pid_t child;

    printf("\nTry to create new process.\n");
    child = fork();

    switch(child)
    {
        case -1:  // fault
            perror("fork.\n");
            exit(EXIT_FAILURE);
        case 0:    // child process
            printf("This is child.\n");
        printf("\tchild pid is %d\n", getpid());
        printf("\tchild ppid is %d\n", getppid());
            exit(EXIT_SUCCESS);

        default:  // father process
        waitpid(child, &stat, 0);
            printf("This is parent.\n");
        printf("\tparent pid is %d\n", getpid());
        printf("\tparent ppid is %d\n", getppid());
        printf("\tchild exited with %d\n", stat);
    }

    exit(EXIT_SUCCESS);
}
程序执行后的结果为:
This is child.
    child pid is 3542
    child ppid is 3535
This is parent.
    parent pid is 3535
    parent ppid is 3534
    child exited with 0
    
Program exited normally.

由此可见:
    程序是成功执行了语句perror("fork.\n")。
但本人就不明白,成功执行后不是返回值0,然后下面的switch语句执行,就只会执行case 0的情况么,接着就会exit(EXIT_SUCCESS)退出程序,为什么还有后面的结果呢???
请指点一下fork()调用的执行流程,谢谢!!!!
    

回复列表 (共3个回复)

沙发

fork()是进程分支,执行后将父进程的数据复制一份给子进程,唯一不同的是父进程中fork()的返回值是子进程的PID,子进程的返回值是0。

板凳

看结果好像对了啊?

3 楼

可以去看看
 linux/kernel/fork.c

我来回复

您尚未登录,请登录后再回复。点此登录或注册