• 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),会受到子进程影响

  • 相关阅读:
    Maven基础概念
    虚拟机的发展史:从分时系统到容器化
    面试难点:Mybatis 中的 DAO 接口和 XML 文件里的 SQL 是如何建立关系的?
    水声信号调制方式智能识别技术
    Restyle起来!
    2022 极术通讯-基于安谋科技 “星辰” STAR-MC1的灵动MM32F2570开发板深度评测
    springboot集成netty实现websocket
    学习Source Generators之了解Source Generators的应用场景
    【LeetCode】面试题 17.19. 消失的两个数字
    长篇图解etcd核心应用场景及编码实战
  • 原文地址:https://blog.csdn.net/2301_78772787/article/details/134431484