Linux生成子进程函数fork()

版权声明:所有的博客都是个人笔记,交流可以留言或者加QQ:2630492017 https://blog.csdn.net/qq_35976351/article/details/85259974

一片非常详细的文章:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void parentProcess(int n) {
  for (int i = 0; i < n; ++i) {
    printf("Parent: %d\n", i);
    sleep(1);  // 睡眠一秒防止执行过快
  }
}

void childProcess(int n) {
  for (int i = 0; i < n; ++i) {
    printf("Child: %d\n", i);
    sleep(1); 
  }
}

int main() {
  pid_t pid;
  pid = fork();
  if (pid == 0) {
    childProcess(10);
  } else {
    parentProcess(10);
  }
  return 0;
}

补充说明:如果父进程先创建了一些文件,然后在fork出一些子进程,那么子进程会和父进程共享内核的资源。举例说明:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>

#define MAXN_BUFFER_SIZE 20

int main() {
  int fd = open("./text.txt", O_CREAT | O_RDWR);
  if (fd < 0) {
    perror("open() error\n");
    exit(EXIT_FAILURE);
  } 
  
  pid_t cpid = fork();
  if (cpid == 0) {  // 子进程
    const char* msg = "child process\n";
    if (write(fd, msg, strlen(msg)) < 0) {
      perror("child write() error\n");
    }
  } else {  // 父进程
    const char* msg = "parent process\n";
    if (write(fd, msg, strlen(msg)) < 0) {
      perror("parent write() error\n");
    }
    wait(NULL);  // 等待子进程结束
    exit(EXIT_SUCCESS);
  }
}

此时,文件的内容是:

parent process
child process

可以看出,子进程复制了父进程的fd,而且对应了相同的内核资源。但是复制的时候,有很多是不能复制的,具体参照fork函数的man手册。

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/85259974
今日推荐