概述

◆ fork系统调用是用于创建进程的
◆ fork创建的进程初始化状态与父进程一样
◆ 系统会为fork的进程分配新的资源
◆ fork系统调用无参数
◆ fork会返回两次,分别返回子进程id和0
◆ 返回子进程id的是父进程,返回0的是子进程

实际操作

  1. #include <iostream>
  2. #include <cstring>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. using namespace std;
  6. int main()
  7. {
  8. pid_t pid;
  9. int num = 888;
  10. pid = fork();
  11. if(pid == 0){
  12. cout << "这是一个子进程." << endl;
  13. cout << "num in son process: " << num << endl;
  14. while(true){
  15. num += 1;
  16. cout << "num in son process: " << num << endl;
  17. sleep(1);
  18. }
  19. }
  20. else if(pid > 0){
  21. cout << "这是一个父进程." << endl;
  22. cout << "子进程id: " << pid << endl;
  23. cout << "num in father process: " << num << endl;
  24. while(true){
  25. num -= 1;
  26. cout << "num in father process: " << num << endl;
  27. sleep(1);
  28. }
  29. }
  30. else if (pid < 0){
  31. cout << "创建进程失败." << endl;
  32. }
  33. return 0;
  34. }