• Linux系统编程——进程中vfork函数


    函数原型

    pid_t vfork(void);//pid_t是无符号整型

    所需头文件

    1. #include
    2. #include

    功能

    vfork() 函数和 fork() 函数一样都是在已有的进程中创建一个新的进程,但它们创建的子进程是有区别的。

    返回值

    成功子进程中返回 0,父进程中返回子进程 ID
    失败返回 -1

    vfork与fork的区别

    关键区别一:

    fork执行时无先后顺序,父进程与子进程会争夺执行 

    vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行

    代码验证

    1. #include
    2. #include
    3. #include
    4. int main()
    5. {
    6. int fork_t = 0;
    7. fork_t = fork();
    8. if(fork_t > 0)
    9. {
    10. while(1)
    11. {
    12. printf("This is father\n");
    13. sleep(1);
    14. }
    15. }
    16. else if(fork_t == 0)
    17. {
    18. while(1)
    19. {
    20. printf("This is child\n");
    21. sleep(1);
    22. }
    23. }
    24. return 0;
    25. }

    1. #include
    2. #include
    3. #include
    4. #include
    5. int main()
    6. {
    7. int vfork_t = 0;
    8. int count = 0;
    9. vfork_t = vfork();
    10. if(vfork_t > 0)
    11. {
    12. while(1)
    13. {
    14. printf("This is father\n");
    15. sleep(1);
    16. }
    17. }
    18. else if(vfork_t == 0)
    19. {
    20. while(1)
    21. {
    22. printf("This is child\n");
    23. sleep(1);
    24. count++;
    25. if(count >= 3)
    26. {
    27. exit(-1);//输出三次子进程,之后退出
    28. }
    29. }
    30. }
    31. return 0;
    32. }

    第一部分代码可见fork函数中的父进程和子进程会争夺输出,而第二部分的vfork函数会在子进程输出3次退出之后再执行父进程。


    关键区别二:

    fork中子进程会拷贝父进程的所有数据,子进程是父进程的地址空间

    vfork中子进程共享父进程的地址空间

    代码验证

    1. #include
    2. #include
    3. #include
    4. int main()
    5. {
    6. int fork_t = 0;
    7. int a = 10;
    8. fork_t = fork();
    9. if(fork_t != 0)
    10. {
    11. printf("This is father,a = %d\n",a);
    12. }
    13. else
    14. {
    15. printf("This is child,a = %d\n",a);
    16. }
    17. return 0;
    18. }

    1. #include
    2. #include
    3. #include
    4. #include
    5. int main()
    6. {
    7. int vfork_t = 0;
    8. int count = 0;
    9. vfork_t = vfork();
    10. if(vfork_t > 0)
    11. {
    12. while(1)
    13. {
    14. printf("count = %d\n",count);
    15. printf("This is father\n");
    16. sleep(1);
    17. }
    18. }
    19. else if(vfork_t == 0)
    20. {
    21. while(1)
    22. {
    23. printf("This is child\n");
    24. sleep(1);
    25. count++;
    26. if(count >= 3)
    27. {
    28. exit(0);
    29. }
    30. }
    31. }
    32. return 0;
    33. }

    第一部分代码可知,在父进程中定义a,调用fork函数时,父进程与子进程打印a的值一样,说明子进程会拷贝父进程的所有数据(父进程的只打印自己的值,不会收子进程影响);第二部分代码可知,在子进程结束之后,才会执行父进程,且子进程中数值发生改变,在父进程调用时会发生改变(一开始父进程a=0,调用后a=3),会受到子进程影响

  • 相关阅读:
    Baumer工业相机堡盟工业相机使用BGAPISDK将工业相机设为Burst模式以及该模式的优势以及行业应用(C#)
    零基础学Java有哪些必看书?推荐这5本
    01-docker基础
    定时器方案,红黑树,时间轮
    迎接金九银十的狂风暴雨,最强Java面经八股文,跳槽必备。
    设计模式-访问者(Visitor)模式介绍和使用
    Linux基本指令(一)
    p5.js 3D图形-立方体
    python个人博客毕业设计开题报告
    洛谷P6672 你的生命已如风中残烛
  • 原文地址:https://blog.csdn.net/2301_78772787/article/details/134431484