当前位置:   article > 正文

【Linux】进程—创建进程_linux创建进程

linux创建进程

前言

继续学习Linux进程

目录

前言

一、创建进程

1.fork()函数创建进程

1.1 函数原型:

1.2 代码示例:

1.3 运行结果:

 2.vfork()函数创建进程

 2.1 函数原型:

 2.2 代码示例: 

 2.3 运行结果: 

二、fork()函数与vfork()函数的区别

1.vfork()函数直接父进程存储空间,不拷贝

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

3.fork()函数父进程和子进程都要运行

4.fork()子进程拷贝父进程内存空间

总结


提示:以下是本篇文章正文内容,下面案例可供参考

一、创建进程

1.fork()函数创建进程

1.1 函数原型:

  1. #include <unistd.h>
  2. pid_t fork(void);
  3. /*fork()函数调用成功,返回两次
  4. 返回 0 代表当前进程是子进程
  5. 返回非负数 代表当前进程是父进程
  6. 调用失败 返回-1

1.2 代码示例:

  1. #include<stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. int main()
  5. {
  6. pid_t pid;
  7. int cnt = 0;
  8. pid = fork();
  9. if(pid > 0){
  10. printf("this is father pid = %d \n",getpid());
  11. }else if(pid == 0){
  12. printf("this is person pid,person pid=%d\n",getpid());
  13. }
  14. return 0;
  15. }
  16. ~
  17. ~

 1.3 运行结果:

 

 2.vfork()函数创建进程

 2.1 函数原型:

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. pid_t vfork(void);

2.2 代码示例: 

  1. #include<stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include<stdlib.h>
  5. int main()
  6. {
  7. pid_t pid;
  8. int cnt = 0;
  9. pid = vfork();
  10. if(pid > 0){
  11. while(1){
  12. printf("this is father pid = %d \n",getpid());
  13. sleep(2);
  14. }
  15. }else if(pid == 0){
  16. while(1){
  17. printf("this is person pid,person pid=%d\n",getpid());
  18. sleep(2);
  19. cnt++;
  20. if(cnt == 3){
  21. exit(0);
  22. }
  23. }
  24. }
  25. return 0;
  26. }
  27. ~
  28. ~

2.3 运行结果: 

 

二、fork()函数与vfork()函数的区别

1.vfork()函数直接父进程存储空间,不拷贝

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

3.fork()函数父进程和子进程都要运行

4.fork()子进程拷贝父进程内存空间


总结

理解进程的创建,fork()函数和vfork()函数,下一个博客总结学习进程的退出。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/660440
推荐阅读
相关标签
  

闽ICP备14008679号