#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
// 创建子进程
pid_t pid = fork();
if (pid < 0) {
// 如果fork失败,返回错误信息
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
// 子进程代码块
printf("This is the child process. PID: %d\n", getpid());
} else {
// 父进程代码块
printf("This is the parent process. PID: %d, Child PID: %d\n", getpid(), pid);
// 等待子进程结束
wait(NULL);
printf("Child process has finished.\n");
}
return 0;
}
#include <stdio.h>: 包含标准输入输出库,用于 printf 和 fprintf 函数。#include <unistd.h>: 包含 fork 函数的声明。#include <sys/wait.h>: 包含 wait 函数的声明,用于等待子进程结束。pid_t pid = fork();: 调用 fork 函数创建一个新进程(子进程)。fork 返回两次:在父进程中返回子进程的 PID,在子进程中返回 0。如果 fork 失败,则返回 -1。if (pid < 0): 检查 fork 是否失败。else if (pid == 0): 如果 pid 为 0,表示当前是子进程,执行子进程的代码块。else: 如果 pid 不为 0,表示当前是父进程,执行父进程的代码块。wait(NULL);: 父进程调用 wait 函数等待子进程结束。这可以防止子进程成为僵尸进程。return 0;: 程序正常结束。这个示例展示了如何使用 fork 创建一个新的子进程,并区分父进程和子进程的代码执行路径。
上一篇:重启服务器命令linux
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站