进程间通信IPC——管道(2)

①在读管道的时候:
1. 管道中有数据, read 返回实际读到的字节数。
2. 管道中无数据:
     (1) 管道写端被全部关闭,read 返回 0 ( 好像读到文件结尾 )
     (2) 写端没有全部被关闭,read 阻塞等待(不久的将来可能有数据递达,此时会让出 cpu)
② 在写管道的时候:
1. 管道读端全部被关闭, 进程异常终止 ( 也可使用捕捉 SIGPIPE 信号,使进程不终止 )
                                 
2. 管道读端没有全部关闭:
          (1) 管道已满,write 阻塞。
          (2) 管道未满,write 将数据写入,并返回实际写入的字节数。

进程间通信练习1:

实现ls | wc -l,父进程执行ls ,子进程执行wc -l
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

void sys_err(const char* str)
{
    perror(str);
    exit(1);
}

int main(int argc, char* argv[])
{
    int ret;
    int fd[2];
    pid_t pid;

    char buf[1024];

    ret=pipe(fd);
    if (ret==-1)
        sys_err("pipe error");

    pid=fork();

    //father process execute 'ls'
    if(pid>0){
        dup2(fd[1],1);
        close(fd[0]);
        execlp("ls","ls",NULL);
        close(fd[1]);
    }
    else if(pid==0){
        close(fd[1]);
        dup2(fd[0],STDIN_FILENO);
    //  printf("%s",buf);
        execlp("wc","wc","-l",NULL);
        close(fd[0]);
    }
    return 0;
}

进程间通信练习2:

兄弟进程分别执行ls ,wc -l

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

void sys_err(const char* str)
{
    perror(str);
    exit(1);
}

int main(int argc, char* argv[])
{
    int ret;
    int fd[2];
    pid_t p_pid;
    pid_t pid[2];
    char buf[1024];
    ret=pipe(fd);

    if (ret==-1)
        sys_err("pipe error");

    for(int i=0;i<2;i++)
    {   
        pid[i]=fork();
        if(pid[i]==0)
        {
            if(i==0)
            {
                dup2(fd[1],1);
                close(fd[0]);
                execlp("ls","ls",NULL);
                close(fd[1]);
            }
            if(i==1)
            {
                close(fd[1]);
                dup2(fd[0],STDIN_FILENO);
                execlp("wc","wc","-l",NULL);
                close(fd[0]);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值