管道通信

1.管道通信的特点:
(1)管道是半双工的,先进先出的,它把一个进程的输出和另一个进程的输入连接在一起
(2)一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)从管道的头部读出数据
2.无名管道和有名管道分别适用的进程是什么?
无名管道用于有血缘关系进程之间的通信;有名管道用于运行同一个系统中的任意两个进程间的通信
3.管道
Pipe
原型:int pipe(int filedes[2])
参数:新建的两个描述符由filedes数组返回。filedes[0]表示管道的读取端,filedes[1]表示管道的写入端
返回值:成功:0;出错:-1
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>



int main()
{
    int ret;
    int count=0;
    pid_t pid;
    int fd[2]={0};
    ret=pipe(fd);//before make pid 
    if(-1==ret)
    {
        perror("pipe");
        exit(1);
    }
    pid=fork();
    if(-1==pid)
    {
        perror("fork");
        exit(1);
    }
    else if(0==pid)
    {
        count++;
        printf("Child Process :count=%d\n",count);
        ret=write(fd[1],&count,sizeof(count));
        if(-1==ret)
        {
            perror("write");
            exit(1);
        }
    }
    else
    {
        ret=read(fd[0],&count,sizeof(count));
        if(-1==ret)
        {
            perror("read");
            exit(1);
        }
        count++;
        printf("Parent Process:count=%d\n",count);
        waitpid(pid,NULL,0);
    }
    return 0;
}



4.有名管道
mkfifo
原型:int mkfifo(const char *filename,mode_t mode)
函数的参数:filename:有名管道的路径,名称。Mode:管道的方式
O_NONBLOCK:FIFO打开的时候会立刻返回,非阻塞

返回值:成功:0;出错:-1


写入

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd;
    int ret;
    char buf[100]={0};
    fd=open("2.txt",O_WRONLY);
    if(-1==fd)
    {
        perror("open");
        exit(1);
    }
    while(1)
    {
        scanf("%s",buf);
        ret=write(fd,buf,strlen(buf));
        if(-1==ret)
        {
            perror("write");
            exit(1);
        }
        if(!strncmp(buf,"bye",3))
        {
            break;
        }
        memset(buf,0,sizeof(buf));
    }

    return 0;
}


读取

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>



int main()
{
    int ret,fd;
    char buf[100]={0};
    ret=mkfifo("2.txt",O_CREAT|O_EXCL);
    if(-1==ret)
    {
        perror("mkfifo");
        exit(1);
    }
    fd=open("2.txt",O_RDONLY);
    if(-1==fd)
    {
        perror("open");
        exit(1);
    }
    while(1)
    {
        ret=read(fd,buf,sizeof(buf));
        if(-1==ret)
        {
            perror("read");
            exit(1);
        }
        if(!strncmp(buf,"bye",3))
        {
            break;
        }
        printf("Read from Fifo:%s\n",buf);
        memset(buf,0,sizeof(buf));
    }
    unlink("2.txt");

    return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值