fork()函数
介绍
fork()函数
fork()函数通过系统调用创建一个与原来进程几乎完全相同的进程,也就是两个进程可以做完全相同的事,但如果初始参数或者传入的变量不同,两个进程也可以做不同的事。
一次调用,两次返回。如果返回值为0,则表示当前子进程中;若大于0,则说明在父进程中,返回值为父进程的pid。
forks.c运行结果及分析
/*
* forks.c - Examples of Unix process control
*/
#include <stdlib.h> //引入standard library标准库头文件,包含常用的系统函数
#include <stdio.h> //引入标准输入输出头文件
#include <unistd.h> //引入unix类系统定义符号常量的头文件,
#include <sys/types.h> //引入Linux系统基本数据类型的头文件
#include <sys/wait.h> //引入wait()和waitpid()两个函数
#include <signal.h> //引入信号处理函数
Fork0
代码内容
/*
* fork0 - The simplest fork example
* Call once, return twice
* Creates child that is identical to parent
* Returns 0 to child process
* Returns child PID to parent process
*/
void fork0()
{
if (fork() == 0) {
printf("Hello from child\n");
}
else {
printf("Hello from parent\n");
}
}
运行结果
简要分析
fork创建进程,一次调用两次返回,我的运行结果说明子进程在父进程后面运行。父进程的ID是29846,子进程的ID是29847
Fork1
代码内容
/*
* fork1 - Simple fork example
* Parent and child both run same code
* Child starts with identical private state
*/
void fork1()
{
int x = 1;
pid_t pid = fork();
if (pid == 0) {
printf("Child has x = %d\n", ++x);
}
else {
printf("Parent has x = %d\n", --x);
}
printf("Bye from process %d with x = %d\n", getpid(), x);
}
运行结果
简要分析
子进程和父进程都运行了一次 Bye from process %d with x = %d\n ,说明子进程和父进程是独立的。
Fork2
代码内容
/*
* fork2 - Two consecutive forks
* Both parent and child can continue forking
* Ordering undetermined
*/
void fork2()
{
printf("L0\n");
fork();
printf("L1\n");
fork();
printf("Bye\n");
}
运行结果
简要分析
此结果说明父进程和子进程都可以创建子进程, 创建的先后顺序没有规定
Fork3
代码内容
/*
* fork3 - Three consective forks
* Parent and child can continue forking
*/
void fork3()
{
printf("L0\n");
fork();
printf("L1\n");
fork();
printf("L2\n");
fork();
printf("Bye\n");
}
运行结果
简要分析
三次fork的图如下,我的电脑运行结果是其中一种可能情况。
Fork4
代码内容
/*
* fork4 - Nested forks in parents
*/
void fork4()
{
printf("L0\n");
if (fork() != 0) {
printf("L1\n");
if (fork() != 0) {
printf("L2\n"