进程间通信--管道(半双工)

..........................................pipe.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#if 0
//对于命名管道的操作与文件操作非常相似,对文件操作中使用的函数read(),write(),close()
//等函数都可以是用来对管道进行操作
//半双工管道的读写---父子进程间的通信
int main()
{
    pid_t pid; //创建进程号的类型定义:pid_t  实际上就是int类型的
    int fd[2];
    int res = pipe(fd);//必须在系统调用fork()之前调用pipe(),
    if(res == -1)
    {
        printf("create pipe error.\n");
        exit(1);
    }
    pid = fork();

    if(pid == 0)  //子进程从管道中获取数据
    {
        char buf[256];
        close(fd[1]); //fd[1](管道写端)写数据
        read(fd[0],buf,256);
        printf("From Parent Msg:>%s\n",buf);
        close(fd[0]);
    }
    else if(pid>0)  //父进程向管道中写数据
    {
        char *msg = "Good Good Study,Day Day up.";
        close(fd[0]); //fd[0](管道读端)读数据
        write(fd[1],msg,strlen(msg)+1); //strlen求得字符串世纪长度
        close(fd[1]);

        int status;
        wait(&status);
     }
    else
    {
        exit(1);
    }
    return 0;
}
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值