#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
函数的作用:用于创建子进程。
返回值:
fork()的返回值会返回两次。一次是在父进程,一次是在子进程。
父进程中:返回创建的子进程的ID,返回-1代表创建失败,并且设置errno
在子进程中,返回0.
如何区分:通过fork返回值。
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
int main() {//创建子进程pid_t pid = fork();//判断是父进程还是子进程if(pid > 0) {printf("pid: %d\n", pid);printf("I am parent process, pid : %d, ppid : %d\n", getpid(), getppid());} else if(pid == 0) {printf("I am child process, pid : %d, ppid : %d\n", getpid(), getppid());}for(int i = 0; i < 5; i++) {printf("i : %d\n", i);}return 0;
}
The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content. Memory writes, file mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect the other.
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
int main() {//创建子进程pid_t pid = fork();int num = 11;//判断是父进程还是子进程if(pid > 0) {printf("pid: %d\n", pid);printf("parent num : %d\n", num);num += 10;printf("parent num : %d\n", num);printf("I am parent process, pid : %d, ppid : %d\n", getpid(), getppid());} else if(pid == 0) {printf("child num : %d\n", num);num += 20;printf("child num : %d\n", num);printf("I am child process, pid : %d, ppid : %d\n", getpid(), getppid());}for(int i = 0; i < 5; i++) {printf("i : %d\n", i);}return 0;
}
读时共享,写时拷贝