fork
by
fork 函数
代码示例
创建子进程
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid = fork(); // 创建子进程
if (pid < 0) {
// fork 失败
perror("fork failed");
return 1;
} else if (pid == 0) {
// 子进程执行
printf("This is the child process. PID = %d, Parent PID = %d\n", getpid(), getppid());
} else {
// 父进程执行
printf("This is the parent process. PID = %d, Child PID = %d\n", getpid(), pid);
}
return 0;
}
循环创建子进程
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
int n = 3; // 要创建的子进程数量
for (int i = 0; i < n; i++) {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
// 子进程:打印信息,退出循环,防止创建孙子进程
printf("Child process %d: PID = %d, PPID = %d\n", i+1, getpid(), getppid());
return 0; // 子进程结束
}
// 父进程继续循环创建下一个子进程
}
// 父进程等待子进程完成(简略,未写 wait())
sleep(1); // 确保子进程有时间输出
printf("Parent process: PID = %d\n", getpid());
return 0;
}