Linux系统调用fork()创建两个子进程示例
Linux系统调用fork()创建两个子进程示例
本文将展示如何在Linux系统中使用fork()系统调用创建两个子进程。
代码示例:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// 子进程1
printf('This is child process 1\n');
} else if (pid1 > 0) {
// 父进程
pid2 = fork();
if (pid2 == 0) {
// 子进程2
printf('This is child process 2\n');
} else if (pid2 > 0) {
// 父进程
printf('This is parent process\n');
} else {
// fork()失败
perror('fork');
return 1;
}
} else {
// fork()失败
perror('fork');
return 1;
}
return 0;
}
运行结果:
This is parent process
This is child process 1
This is child process 2
解释:
- 程序使用
fork()系统调用创建两个子进程。 pid1和pid2分别存储第一次和第二次fork()的返回值。- 由于
fork()函数返回两次,一次在父进程中,一次在子进程中,因此if-else语句根据返回值判断当前进程类型。 pid == 0表示当前进程为子进程,pid > 0表示当前进程为父进程,pid < 0表示fork()调用失败。- 程序输出表明成功创建了两个子进程。
总结:
本文通过代码示例和解释说明了如何使用fork()系统调用在Linux系统中创建两个子进程。这只是fork()系统调用的基本应用,实际应用中还会涉及进程间通信、信号处理等更多内容。
原文地址: https://www.cveoy.top/t/topic/nEQd 著作权归作者所有。请勿转载和采集!