Skip to content

使用fork系统调用创建进程

  • fork系统调用的事用于创建进程的
  • fork创建的进程初始化状态与父进程一样
  • 系统会为fork的进程分配新的资源

fork调用介绍

  • fork系统调用无参数
  • fork会返回两次,分别返回进程id和0
  • 返回子进程id的是父进程,返回0的是子进程

fork 例子

#include <iostream>
#include <cstring>
#include <stdio.h>
#include <unistd.h>

using namespace std;

int main()
{
    pid_t pid;

    int num = 888;
    pid = fork();

    if(pid == 0){
        cout << "这是一个子进程." << endl;
        cout << "num in son process: " << num << endl;
        while(true){
            num += 1;
            cout << "num in son process: " << num << endl;
            sleep(1);
        }
    }
    else if(pid > 0){
        cout << "这是一个父进程." << endl;
        cout << "子进程id: " << pid << endl;
        cout << "num in father process: " << num << endl;
        while(true){
            num -= 1;
            cout << "num in father process: " << num << endl;
            sleep(1);
        }
    }
    else if (pid < 0){
        cout << "创建进程失败." << endl;
    }
    return 0;
}