fork的例子

2023-11-17

//以下是下列代码的头文件
/*
 * forks.c - Examples of Unix process control
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h> 
#include <signal.h> 

(零)

/*
 * 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创建一个子进程,子进程打印出(“Hello from child”);
父进程打印出(“Hello from parent”);

(一)

/* 
 * 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);
     }

在这里插入图片描述使用getpid可以得到创建子进程的ID号
父进程和子进程是独立运行的

(二)

/*
 * 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 - 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");
}

在这里插入图片描述
在这里插入图片描述

(四)

/* 
 * fork4 - Nested forks in parents
 */
 void fork4()
{
    printf("L0\n");
    if (fork() != 0) {
 printf("L1\n");    
 if (fork() != 0) {
     printf("L2\n");
 }
    }
    printf("Bye\n");
}

在这里插入图片描述
在这里插入图片描述

(五)

/*
 * fork5 - Nested forks in children
 */
void  fork5()
{
    printf("L0\n");
    if(fork()==0){
           printf("L1\n");
           if(fork()==0){
                printf("L2\n");
            }
         }
         printf("Bye\n");
  }
``
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191129175336666.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191129180351581.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3oxOTExNzI1MTQ1,size_16,color_FFFFFF,t_70)


**(六)**

void cleanup(void) {
printf(“Cleaning up\n”);
}
/*

  • fork6 - Exit system call terminates process
  • call once, return never
    */
    void fork6()
    {
    atexit(cleanup);
    fork();
    exit(0);
    }
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191129180955952.png)

**(七)**

/*

  • fork7 - Demonstration of zombies.
  • Run in background and then perform ps
    /
    void fork7()
    {
    if (fork() == 0) {
    /
    Child /
    printf(“Terminating Child, PID = %d\n”, getpid());
    exit(0);
    } else {
    printf(“Running Parent, PID = %d\n”, getpid());
    while (1)
    ; /
    Infinite loop */
    }
    }
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191129181226323.png)
子进程正常退出,父进程进入死循环,所以要使用Ctrl+C终止进程

**(八)**

/*

  • fork8 - Demonstration of nonterminating child.
  • Child still running even though parent terminated
  • Must kill explicitly
    /
    void fork8()
    {
    if (fork() == 0) {
    /
    Child /
    printf(“Running Child, PID = %d\n”,
    getpid());
    while (1)
    ; /
    Infinite loop */
    } else {
    printf(“Terminating Parent, PID = %d\n”,
    getpid());
    exit(0);
    }
    }
    ``
    在这里插入图片描述子进程进入死循环,父进程正常退出,回收子进程。

(九)

/*
 * fork9 - synchronizing with and reaping children (wait)
 */
 void fork9()
 {
      int child_status;
      if(fork()==0){
            printf("HC:hello from child\n");
            exit(0);
         }else{
                   printf("HP:hello from parent\n");
                   wait(&child_status);
                   printf("CT:child has terminated\n");
           }
           printf("Bye\n");
    }

在这里插入图片描述
wait表示等待子进程结束以后执行wait后续的代码,所以最后打印出CT:child has terminated

(十)

#define N 5
/* 
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
 void fork10()
 {
       pid_t pid[N];
       int i,child_status;
       for(i=0;i<N;i++)
               if((pid[i]=fork())==0){
                     exit(100+i);
                     }
          for(i=0;i<N;i++){
                    pid_t wpid=wait(&child_status);
                    if(WIFEXITED(child_status));
                          printf("Child %d terminated with exit status %d\n",wpid,WEXITSTATUS(child_status));
                       else
                            printf("Child %d terminate abnormally\n",wpid);
                }
      }

在这里插入图片描述
创建了5个子进程,并且将退出状态码返回给父进程。

(十一)

/*
*fork11
*Reaps children in reverse order
*/
void fork11()
{
      pid_t   pid[N];
      int i;
      int child_status;
      for(i=0;i<N;i++)
                if((pid[i]=fork())==0)
                      exit(100+i);
         for(i=N-1;i>=0;i--){
               pid_t  wpid=waitpid(pid[i],&child_status,0);
               if(WIFEXITED(child_status))
                     printf("Child %d terminated with exit status %d\n",wpid,WEXITSTATUS(child_status));
                     else
                           printf("Child %d terminate abnormally\n",wpid);
             }
    }

在这里插入图片描述相比于fork10,这里将输出进行排序输出

(十二)

/*
 * fork12 - Sending signals with the kill() function
 */
 void fork12()
 {
      pid_t   pid[N];
      int i;
      int child_status;
      for(i=0;i<N;i++)
            if((pid[i]=fork())==0){
                 while(1);
              }
    for(i=0;i<N;i++){
           printf("Killing process %d \n",pid[i]);
           kill(pid[i],SIGINT);
     }
     for(i=0;i<N;i++){
            pid_t  wpid=wait(&child_status);
            if(WIFEXITED(child_status))
                  printf("Child %d terminated with exit status %d\n",wpid,WEXITSTATUS(child_status));
              else
                  printf("Child %d terminated abnormally\n",wpid);
         }
     }




`
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191129231017804.png)
由于子进程进入了死循环,所以使用kill将子进程都杀死,因为子进程没有创建成功,所以执行了(Child %d terminated abnormally")


**(十三)**

/*
*int_handler -SIGINT handler
/
void int_handler(int sig)
{
printf(“Process %d received signal %d\n”,getpid(),sig);
exit(0);
/

*fork13 -Simple signal handler example
*/
void fork13()
{
pid_t pid[N];
int i;
int child_status;
signal(SIGINT,int_handler);
for(i=0;i<N;i++)
if((pid[i]=fork())==0){
while(1);
}
for(i=0;i<N;i++){
printf(“Killing process %d\n”,pid[i]);
kill(pid[i],SIGINT);
}
for(i=0;i<N;i++){
pid_t wpid=wait(&child_status);
if(WIFEXITED(child_status))
printf(“Child %d terminated with exit status %d\n”,wpid,WEXITSTATUS(child_status));
else
printf(“Child %d terminated abnormally\n”,wpid);
}
}

``
在这里插入图片描述
fork13相比与fork12将处理函数转给自定义的函数进行处理。

(十四)

/*
 * child_handler - SIGCHLD handler that reaps one terminated child
 */
 int ccount = 0;
 void child_handler(int sig)
 {
        int child_status;
        pid_t pid = wait(&child_status);
        ccount--;
         printf("Received SIGCHLD signal %d for process %d\n", sig, pid); 
         fflush(stdout);
  }
 void fork14()
 {
       pid_t pid[N];
       int i;
       ccount = N;
        signal(SIGCHLD, child_handler);
          for (i = 0; i < N; i++) {
                if ((pid[i] = fork()) == 0) {
                      sleep(1);
                       exit(0); 
                   }
            }
            while(ccount>0);
    }

在这里插入图片描述

(十五)

/*
 * child_handler2 - SIGCHLD handler that reaps all terminated children
 */
 void child_handler2(int sig)
 {
       int child_status;
       pid_t pid;
        while ((pid = wait(&child_status)) > 0) {
                    ccount--;
                    printf("Received signal %d from process %d\n", sig, pid); 
                    fflush(stdout); 
               }
}
/*
 * fork15 - Using a handler that reaps multiple children
 */
 void fork15()
 {
        pid_t pid[N];
        int i;
        ccount = N;
        signal(SIGCHLD, child_handler2);
        for (i = 0; i < N; i++)
                   if ((pid[i] = fork()) == 0) {
                         sleep(1);
                         exit(0);
                     }
           while(ccount>0){
                pause();
           }
    }
                   

在这里插入图片描述这里使用pause将暂停,先让子进程的5个循环做完。

(十六)

/* 
 * fork16 - Demonstration of using /bin/kill program 
 */
 void fork16() 
 {
        if (fork() == 0) {
             printf("Child1: pid=%d pgrp=%d\n",
                      getpid(), getpgrp());
               if (fork() == 0)
                       printf("Child2: pid=%d pgrp=%d\n",
                                  getpid(), getpgrp());
                  while(1);
          }
    }

在这里插入图片描述

(十七)

/* 
 * Demonstration of using ctrl-c and ctrl-z 
 */
 
void fork17() 
{
           if (fork() == 0) {
                   printf("Child: pid=%d pgrp=%d\n",
                        getpid(), getpgrp());
    } else {
                 printf("Parent: pid=%d pgrp=%d\n",
        getpid(), getpgrp());
  }
    while(1);
} 

在这里插入图片描述
进入死循环时,可以使用Ctrl+c进行终止,使用Ctrl+z进行挂起

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

fork的例子 的相关文章

随机推荐

  • RabbitMQ第一个实操小案例

    文章目录 二 RabbitMQ实操小案例 2 1 Hello World 2 2 Spring AMQP 二 RabbitMQ实操小案例 进入RabbitMQ的官网 选择 Document 菜单项 然后点击Tutorials下的 Get S
  • 使用idea将一个web项目部署到tomcat上

    使用idea将一个web项目部署到tomcat上 点击Run Edit Configurations 单击 找到tomcat server local 选定tomcat版本 点击Fix 单击Apply OK 最终成果
  • centos linux 安装RDMA Soft-RoCE

    RoCE既可以通过硬件实现 也可以通过软件实现 Soft RoCE 是 RDMA 传输的软件实现 什么是Soft RoCE softRoCE的目标是在所有支持以太网的设备上都可以部署RDMA传输 可以使不具备RoCE能力的硬件和支持RoCE
  • vim 编辑器 bash文件测试

    1 编辑 x 删除光标所在处字符 x 删除光标所在处开始往后的 个字符 d 删除命令 dd 删除光标所在处一整行 d 删除光标所在处往后的 行 2 末行模式 start end eg 3 4 10 9 表示光标所在行 最后一行 2 当前到倒
  • Win10下安装Tensorflow

    建议安装AnacondaWindows下 只有python3能安装Tensorflow 1 打开命令行窗口 创建conda环境 conda create n tensorflow python 3 x 对应着自己的python版本 必须要3
  • 【前端】求职必备知识点2-CSS:优先级、盒子模型、标准流、浮动流、定位流

    文章目录 CSS优先级 盒子模型 标准流 浮动流 定位流 标准流 浮动流 定位流 思维导图 CSS优先级 class类选择器 属性选择器 伪类 的权值为10 元素选择器 伪元素选择器权值为1 属性选择器 如 将有title的元素变为红色 t
  • Obsidian Tasks插件介绍

    背景 按照之前对 DataView 插件的介绍 对于任务列表的使用其实就可以使用其中的 list 插件完成的 但是 DataView 插件只能完成列表的查询功能 而查询功能只能是任务列表中其中一个功能 因此就使用 DataVIew 插件是不
  • java集合List

    Java集合概况 Java集合一直理解的都是片面的 整理一下 将知识组织成面 更便于理解 上图来自Java 集合系列01之 总体框架 如果天空不死 博客园 虽然博主是基于java1 6整理的 但也不碍于我们学习 理解了上图 对于学习java
  • 排序遍历带前缀的文件名

    排序遍历带前缀的文件名 def getTimeId file fileAttrs file split fileTime fileAttrs 0 return fileTime def CleanUpExpireTar backupDir
  • 树莓派4B安装Batocera V35版本 前言

    前言 说说为什么要写这个 原因比较多 我在大学的时候买了树莓派4B 那时正价购买 刷了个OpenWrt系统在宿舍当软路由再跑 毕业之后买了个X86主机当软路由 树莓派就放着吃灰了 大学时期同样买了个北通的游戏手柄 当初为了玩崩坏3购入的 后
  • DDR2 DDR3的区别

    DDR2 DDR3的区别 功耗进一步减少 DDR2内存的默认电压为1 8V 而DDR3内存的默认电压只有1 5V 因此内存的功耗更小 发热量也相应地会减少 值得一提的是 DDR3内存还新增了温度监控 采用了ASR Automatic sel
  • Unity5.x运行场景直接卡死的问题

    今天遇到一个很奇葩的问题 就是电脑中Unity5 x版本的都不能运行场景了 包括新建空的工程也不行 重装unity软件重装VS环境也不行 神奇的是2017 2018 2019版本的都没有问题 并且界面也没有任何报错 爬各种论坛谷歌都没有找到
  • 山海演武传·黄道·第一卷 雏龙惊蛰 第二十二 ~ 二十四章 真龙之剑·星墟列将...

    我是第一次 请你 请你温柔一点 少女一边娇喘着 一边将稚嫩的红唇紧贴在男子耳边 樱桃小嘴盈溢出如兰香气 这样子 人家骑在上面 她紧紧地依偎在某个男子身上 窈窕的身躯与丰盈的酥胸 伴随着男子身体晃动而滑上滑下 起伏不定 啊 不要晃的那样厉害
  • ios appStore上架审核通过后,appStore搜索不到该应用

    问题描述 前两天上架一款ios App 周一到公司看审核已经通过了 去appStore上搜索一直搜索不到 ios appStore connect点击提示该商品在中国大陆没有上架 解决方法 通过app store connect 最下面的联
  • vue3.0 + element Plus实现页面中引入弹窗组件及defineExpose用法

    1 在需要弹窗显示的页面引入你所写的弹窗组件 index html
  • AI革命:AI+算力,霸主即将诞生!

    随着人工智能技术的飞速发展 AI 算力 的结合应用已成为科技行业的热点话题 甚至诞生出 AI 算力 最强龙头 的网络热门等式 该组合不仅可以提高计算效率 还可以为各行各业带来更强大的数据处理和分析能力 从而推动创新和增长 那么对于这个时下的
  • 二维多孔介质图像的粒度分布研究(Matlab代码实现)

    欢迎来到本博客 博主优势 博客内容尽量做到思维缜密 逻辑清晰 为了方便读者 座右铭 行百里者 半于九十 本文目录如下 目录 1 概述 2 运行结果 3 参考文献 4 Matlab代码实现 1 概述 使用流域分割算法对岩石二维二值图像进行粒度
  • Scala深入浅出——从Java到Scala

    本文适合有一定Java基础的 并想系统学习Scala的小伙伴借鉴学习 文章有大量实例 建议自己跑一遍 Scala深入浅出 从Java到Scala Scala 一 介绍 1 什么是Scala 2 特点 3 安装 二 Scala特点 三 sca
  • SecureCRT9.1高亮配色设置

    参考 http zh cjh com qita 1623 html https download csdn net download qq 45698138 88310255 spm 1001 2014 3001 5503 1 创建文件co
  • fork的例子

    以下是下列代码的头文件 forks c Examples of Unix process control include