跳至正文
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
关

搜索

  • https://www.facebook.com/
  • https://twitter.com/
  • https://t.me/
  • https://www.instagram.com/
  • https://youtube.com/
Subscribe

day7练习2

问题描述

使用管道实现兄弟进程间通信。 兄:ls 弟: wc -l 父:等待回收子进程。

题目解析

与练习2题目类似,不再提供解析。

代码实现

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
    pid_t pid;
    int i;
    int n=2;
    int fd[2];
    int ret = pipe(fd);
    if(ret == -1)
    {
        perror("pipe error:");
        exit(1);
    }
    //创建两个子进程
    for(i=0;i<n;i++)
    {
        pid = fork();
        if(pid == 0)
            break;
    }
    //子进程1:兄
    if(i == 0)
    {
        close(fd[0]);
        dup2(fd[1],STDOUT_FILENO);
        execlp("ls","ls",NULL);
    }
    //子进程2:弟
    else if(i == 1)
    {
        close(fd[1]);
        dup2(fd[0],STDIN_FILENO);
        execlp("wc","wc","-l",NULL);

    }
    //父进程
    else
    {
        close(fd[0]);
        close(fd[1]);
        sleep(2);
        for(i=0;i < 2;i++)
        {
            wait(NULL);
        }
    }

    return 0;

}

标签:

centoslinux
作者

yszhang

关注我
其他文章
上一个

day7练习1:使用管道实现父子进程间通信,完成:ls | wc –l。

下一个

day7练习3:统计当前系统中进程由用户运行的进程并输出到文件中

暂无评论!成为第一个。

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Copyright 2026 — 小奥的学习笔记. All rights reserved. Blogsy WordPress Theme