fork和vfork函数

发布时间:2020-07-21 00:47:09 作者:PlayWithYou
来源:网络 阅读:441

fork:

    fork用于派生一个进程。如果成功,父进程返回子进程的ID,子进程中返回0,若出错则返回-1。

主要用途:

    一个进程希望复制自身,从而子父进程能同时执行不同的代码段。

    进程想要执行另一个程序

例如:

#include<stdio.h>
#include<sys/types.h>
#include<stdio.h>
int main()
{
        int count=0;
        pid_t pid;
        pid=fork();     // 创建一个子进程
        if(pid<0)
        {
                printf("error in fork!");
                exit(1);
        }
        else if(pid==0)
        {
                printf("I am the child process,the count is %d,my process ID %d,pid=%d\n",++count,getpid(),pid);
                exit(0);
        }
        else
                printf("I am the parent process,the count is %d,my process ID %d,pid=%d\n",count,getpid(),pid);
        return 0;
}

输出结果:

I am the parent process,the count is 0,my process ID 13981,pid=13982
I am the child process,the count is 1,my process ID 13982,pid=0

从中可以看出,两个进程中,原先就存在的那个被称为父进程,新出现的那个被称为子进程。父子进程的区别除了进程标识符(ID)不同外,变量pid的值也不同,pid存放的是fork的返回值。fork调用的一个奇妙之处就是它仅仅被调用一次,却能返回两次,它可能有三中不同的返回值

    父进程中,返回新建子进程的ID

    子进程中,返回0

    若出错,则返回一个负值。

fork出错的原因有两种:

   1. 当前的进程数已经达到系统规定的上限,

    2.系统内存不足,

fork出错的可能性很小,一般为第一种情况

vfork与fork相同,父进程返回子进程的ID,子进程中返回0,若出错则返回-1。

不同的是:

    fork要拷贝父进程的数据段;而vfork则不需要完全拷贝父进程的数据段,在子进程没有调用exec或exit之前,子进程与父进程共享数据段。

    fork不对父子进程的执行次序进行任何限制,而在vfork调用中,子进程先运行,父进程挂起,直到子进程调用了exec或exit之后,父进程的执行次序才不再有限制。

例如:

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(void)
{
        int count=1;
        int child;
        printf("Before create son, the father's count is %d\n",count);
        child=vfork();  //创建了一个新的进程,此时有两个进程在运行
        if(child < 0)
        {
                printf("error in vfork!\n");
                exit(1);
        }
        if(child==0)
        {
                printf("This is son,his pid id %d and the count is %d\n",getpid(),++count);
                exit(1);
        }
        else
        {
                printf("After son, This is father,his pid is %d and the count is %d, and the child is %d\n",getpid(),count,child);
        }
        return 0;
}

运行结果:

Before create son, the father's count is 1
This is son,his pid id 14049 and the count is 2
After son, This is father,his pid is 14048 and the count is 2, and the child is 14049

从运行结果中,我们可以看出,在子进程中修改了count的值,但是父进程中输出了修改后的值2,而不是初始值1.说明子进程和父进程是共享count的,也就是说,由vfork创建出来的子进程与父进程之间是共享内存区的。另外,有vfork创建的子进程还会导致父进程的挂起,除非子进程执行了exit或者execve才会唤醒父进程。

推荐阅读:
  1. vfork和fork区别
  2. fork和vfork程序验证区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

程序 fork vfork

上一篇:liunx中vi快捷键编辑

下一篇:Python 编程快速上手 让繁琐工作自动化-第九章实践项目 9.8.3消除缺失的编号

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》