fork的使用和循环创建多进程

fork函数

函数原型

#include <unistd.h>
pid_t fork(void);
  • 可以创建一个子进程

  • 父进程返回子进程的pid,子进程返回0

  • getpid()获取当前进程id,getppid()获取父进程的id

  • 循环创建N个子进程模型,每个子进程标识自己的身份

  • 父子进程相同:

    • 刚fork后,data段,text段,堆,栈,环境变量,全局变量,宿主目录位置,进程工作目录位置,信号处理方式
  • 父子进程不同:

    • 进程id、返回值、各自的父进程、进程创建时间、闹钟、未决信号集
  • 父子进程共享:

    • 读时共享、写时复制 ---------- 全局变量
    1. 文件描述符 2. mmap映射区
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

int main(int agrc, char *agrv[])
{
  printf("brfore fork-1-
");
  printf("brfore fork-2-
");
  printf("brfore fork-3-
");
  printf("brfore fork-4-
");
  
  pid_t pid = fork();
  if (pid == -1){
    perror("fork error");
    exit(1);
  }else if (pid==0){
    printf("---child is created
");
  }else if (pid > 0){
    printf("---parent process: my child is %d
", pid);
  }
  printf("end!!");
  
  return 0;
}

循环创建子进程

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

int main(int agrc, char *agrv[])
{
  int i;
  pid_t pid;
  for (i=0; i<5; i++){
    pid = fork();
    if (pid==0){
      break;
    }
  }
  if(i==5){
    sleep(5)
    printf("I'm parent 
");
  }else{
    sleep(i)
      printf("I'm %dth child
", i+1);
  }
  

  
  return 0;
}

原文地址:https://www.cnblogs.com/fandx/p/12518153.html