一片非常详细的文章: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手册。