博客
关于我
操作系统实验之进程管理
阅读量:569 次
发布时间:2019-03-09

本文共 1486 字,大约阅读时间需要 4 分钟。

前言

一、实验要求掌握子进程的创建、父子进程的通信及其原理。

二、实验内容熟悉 Linux 环境基本使用命令,熟悉使用 vi、gdb、gcc 等编程工具或软件。

  • 使用系统调用 fork()创建两个子进程,父进程和子进程并发执行,输出并发执行的消息,如:

  • 父进程正在执行……子进程 1 正在执行……子进程 2 正在执行…

    一段时间后,父进程杀死子进程,然后结束自己的进程,分别显示:


    子进程 1 被父进程杀死子进程 2 被父进程杀死父进程结束

    代码

    #include 
    #include
    #include
    #include
    int main() { int pid; printf("---------------------\n"); printf("父进程正在执行……\n"); pid = fork(); if (pid == 0) { printf("子进程1正在执行……\n"); sleep(2); sleep(3); printf("---------------------\n"); printf("子进程1被父进程杀死\n"); exit(0); } if (pid > 0) { int pid1 = fork(); if (pid1 == 0) { printf("子进程2正在执行……\n"); sleep(2); sleep(3); printf("---------------------\n"); printf("子进程2被父进程杀死\n"); exit(0); } if (pid1 > 0) { sleep(1); printf("---------------------\n"); printf("一段时间后\n"); sleep(3); sleep(2); printf("父进程结束\n"); printf("---------------------\n"); exit(0); } } return 0;}

    运行结果

    运行上述代码,您将在终端或Fullscreen模式下看到以下结果:

    ---------------------父进程正在执行……子进程1正在执行……子进程2正在执行…---------------------一段时间后子进程1被父进程杀死子进程2被父进程杀死父进程结束---------------------

    代码解释

    if 判断语句

    if (pid == 0) {子进程1执行,然后退出}

    if (pid > 0) {生成子进程2}

    sleep() 休眠函数

    sleep(参数)函数用于让进程暂停指定的时间单位(秒)。在上述代码中:sleep(2); 休眠2秒sleep(3); 休眠3秒sleep(1); 休眠1秒sleep(3); 休眠3秒sleep(2); 休眠2秒

    转载地址:http://qtlpz.baihongyu.com/

    你可能感兴趣的文章
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>