fork()创建子进程步骤、函数用法及常见考点(内附fork()过程图)

来源:互联网 发布:linux怎么装ntfs 编辑:程序博客网 时间:2024/05/19 22:48

http://blog.csdn.net/yangcs2009/article/details/39267733

fork()系统调用函数用法

一个现有进程可以调用fork函数创建一个新的进程。

#include《unistd.h>

pid_t fork(void);

返回值:子进程中返回0,父进程中返回子进程的ID,出错返回-1

fork函数被调用一次,但返回两次。两次返回的唯一出别是child process的返回值是0,而父进程的返回值则是child process的进程ID。所以可以通过fork函数的返回值来进入父子进程独有的代码段(但是要借助ifelse(else if else )选择语句)。

注:父子进程共享代码段,但是分别拥有自己的数据段和堆栈段。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

int main()
{
        fork();
        fork();
        fork();
        printf("hello world\n");
        return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

char buf[32] = "this is jim";
int main()
{
        char buf2[32] = "this is tom";
        int pid = fork();
        if(pid ==0)
        {
                printf("this is child ,pid =%d,getppid = %d\n",getpid(),getppid());
                strcpy(buf,"jjj");
                strcpy(buf2,"ttt");
                printf("child:%s\n",buf);
                printf("child:%s\n",buf2);
        }
        else if(pid > 0)
        {
                sleep(2);
                printf("this is parent,childpid=%d,pid=%d\n",getpid(),getppid());
                printf("parent:%s\n",buf);
                printf("parent:%s\n",buf2);

                exit(0);
        }
        else
        {
                printf("error\n");
                exit(1);
        }
        printf("hello,pid = %d\n",getpid());
        return 0;

}

原创粉丝点击