第8章-forks.c运行结果及分析

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");
    }
}
运行结果

fork0

简要分析

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);
}
运行结果

1

简要分析

子进程和父进程都运行了一次 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");
}
运行结果

3

简要分析

此结果说明父进程和子进程都可以创建子进程, 创建的先后顺序没有规定

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的图如下,我的电脑运行结果是其中一种可能情况。
tupian

Fork4

代码内容
/* 
 * fork4 - Nested forks in parents
 */
void fork4()
{
   
    printf("L0\n");
    if (fork() != 0) {
   
	printf("L1\n");    
	if (fork() != 0) {
   
	    printf("L2\n"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值