栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux系统编程 85 兄弟进程通信

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux系统编程 85 兄弟进程通信

学习笔记

使用创建n个子进程的模型,创建兄弟进程,使用循环因子i标示。注意管道的读写行为。
兄:ls -l
弟:wc -l
父:等待子进程回收

$cat brothercommunication.c
#include
#include
#include
#include
#include
#include
void sys_err(const char *str)
{
    perror(str);
    exit(1);
}
int main(int argc, char *argv[])
{
    int fd[2];
    int ret;
    int i;
    pid_t pid;
    ret = pipe(fd);
    if(-1 == ret)
    {
        sys_err("pipe error!");
    }

    for(i =0;i<2;i++)    {
        pid = fork();
        if(pid == -1)
        {
            sys_err("fork error!");
        }
        if(0 == pid)
        {
            break;
        }

    }
    if(2 == i)
    {
        wait(NULL);
        wait(NULL);
    }else if( 0 == i)//xiong
    {
        close(fd[0]);
        dup2(fd[1],STDOUT_FILENO);
        execlp("ls","ls","-l",NULL);
        sys_err("execlp error!");
    }else if (1 == i) //di
    {
        close(fd[1]);
        dup2(fd[0],STDIN_FILENO);
        execlp("wc","wc","-l",NULL);
        sys_err("execlp wc error!");
    }
    return 0;

}

$./brothercommunication 

出问题的原因:

图1

管道是需要单向流动。父进程读端和写端没有关闭。

$cat brothercommunication.c
#include
#include
#include
#include
#include
#include
void sys_err(const char *str)
{
    perror(str);
    exit(1);
}
int main(int argc, char *argv[])
{
    int fd[2];
    int ret;
    int i;
    pid_t pid;
    ret = pipe(fd);
    if(-1 == ret)
    {
        sys_err("pipe error!");
    }

    for(i =0;i<2;i++)    {
        pid = fork();
        if(pid == -1)
        {
            sys_err("fork error!");
        }
        if(0 == pid)
        {
            break;
        }

    }
    if(2 == i)
    {
        close(fd[0]);
        close(fd[1]);
        wait(NULL);
        wait(NULL);
    }else if( 0 == i)
    {
        close(fd[0]);
        dup2(fd[1],STDOUT_FILENO);
        execlp("ls","ls","-l",NULL);
        sys_err("execlp error!");
    }else if (1 == i)
    {
        close(fd[1]);
        dup2(fd[0],STDIN_FILENO);
        execlp("wc","wc","-l",NULL);
        sys_err("execlp wc error!");
    }
    return 0;

}
$./brothercommunication 
4
$ls
brothercommunication  brothercommunication.c  makefile
$ls|wc -l
3

和实际不一样? 为什么?
实际上是一样的!
命令用错了。

$ls -l |wc -l
4
$ls -l
total 28
-rwxrwxr-x 1 ubuntu ubuntu 20272 1月  16 21:11 brothercommunication
-rw-rw-r-- 1 ubuntu ubuntu   797 1月  16 21:11 brothercommunication.c
-rw-rw-r-- 1 ubuntu ubuntu   169 1月  16 20:48 makefile

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/705773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号