管道

管道(pipe):分为匿名管道和命名管道
匿名管道:用于有亲缘关系的两个进程间通信

int pipe2(int pipefd[2], int flags);

#include <stdio.h>
#include <unistd.h>
#include <string.h>
//int pipe(int pipefd[2]);  2只是用于告诉只有两个元素有效
//把pipe两端看做两个文件,pipefd[0]读,pipefd[1]写
void main()
{
    int pipefd[2];
    pipe(pipefd);//相当于以读和写两种方式打开了两个文件

    int pid=fork();
    if(pid<0)
            perror("fork()");
    else if(0==pid)//子进程
    {
        char buf[20]="hello daddy";
        write(pipefd[1],buf,sizeof(buf));//写//如果管道满了,也会阻塞
        //也可以用fwrite写
        read(pipefd[0],buf,sizeof(buf));//如果管道没有数据,父进程会等待
        printf("父进程说:%s\n",buf);

        close(pipefd[0]);
        close(pipefd[1]);
    }
    else//父进程
    {
        char buf[20];
//      wait(NULL);不需要显示等子进程    //阻塞
        read(pipefd[0],buf,sizeof(buf));//如果管道没有数据,父进程会等待
        printf("子进程说:%s\n",buf);

        strcpy(buf,"hi boy");
        write(pipefd[1],buf,sizeof(buf));

        close(pipefd[0]);
        close(pipefd[1]);
    }
}

命名管道命名管道:可用于任意两个进程间通信
(一个在文件中写,另一个在文件中读,只要知道文件名就可以相互通信)

#include <iostream>
#include <fstream>//!!
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
    mkfifo("./data",00664);

    ofstream of("./data");//发消息,创建文件,写入文件
    of<<"有人吗?";       //消息没人收会阻塞

    return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#define PATH "./data"

int main()
{
    ifstream inf("./data");//收消息,读文件
    string msg;            //文件中没有消息会阻塞
    inf>>msg;
    cout<<"收到消息:"<<msg<<endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值