Linux进程间通信---有名管道 代码实现

一、管道通信的注意事项
(1)执行mkfifo file命令来创建一个管道文件。

[admin@localhost code]$ mkfifo pipe
[admin@localhost code]$ ls -l
total 0
'''p'rw-rw-r-- 1 admin admin 0 830 19:52 pipe  //p就代表是管道文件

(2)如果只把管道的写打开,管道是不通的,是写不进去的。

(3)只有把读、写都打开才能写进去。

二、代码示例(一个是写管道、一个读管道)

写管道:

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

int main()
{
    int nFd = 0;
    int nWrLen = 0, nReadLen = 0;;
    char szBuff[BUFSIZ] = {0};

    /* 打开当前目录下的管道文件 */
    nFd = open("pipe", O_RDWR);
    if (-1 == nFd)
    {
        perror("Open fifo failed\n");
        return 1;
    }

    while (1)
    {
        /* 从终端读取数据 */
        memset(szBuff,0,BUFSIZ);
        nReadLen = read(STDIN_FILENO,szBuff,BUFSIZ);

        if(nReadLen > 0)
        {
            /* 往管道写入数据 */
            nWrLen = write(nFd, szBuff, strlen(szBuff)+1);
            if (nWrLen > 0)
            {
                printf("write data successful: %s \n", szBuff);
            }
            else
            {
                perror("write failed:");
            }
        }


    }

}

读管道:

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

int main()
{
    int nFd = 0;
    int  nReadLen = 0;;
    char szBuff[BUFSIZ] = {0};

    /* 打开当前目录下的管道文件 */
    nFd = open("pipe", O_RDWR);
    if (-1 == nFd)
    {
        perror("Open fifo failed\n");
        return 1;
    }

    while (1)
    {
        /* 从管道读取数据 */
        memset(szBuff,0,BUFSIZ);
        nReadLen = read(nFd,szBuff,BUFSIZ);
        if(nReadLen > 0)
        {
            printf("read pipe data: %s\n", szBuff); 
        }   
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmfrm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值