0
点赞
收藏
分享

微信扫一扫

2分钟0基础学会 有名管道的使用(内附C语言代码)

一、创建fifo文件

1、通过命令:mkfifo名字 ;例如:mkfifo fifo

2、通过函数:int mkfifo(const char *pathname,mode_t mode);

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname,mode_t mode);

参数:

-pathname:管道名称的路径

-mode:文件的权限 和 open 的mode是一样的 是一个八进制的数

返回值:

成功:返回0;失败:返回 -1.

注意事项:

向管道中写数据

1、一个只为读而打开一个管道的进程会阻塞,直到另外一个进程只为写而打开管道

2、一个只为写而打开一个管道的进程会阻塞,直到另外一个进程只为读而打开管道

读管道:

管道中有数据,read返回实际读到的字节数

管道中无数据:

管道写端被全部关闭,read返回0(相当于读到文件末尾);

写端没有全部被关闭,read阻塞等待

写管道:

管道读端被全部关闭,进程一场终止(收到SIGPIPE)

管道读端没有全部关闭:

管道已经满了,write会阻塞

管道没有满,write将数据写入,并返回实际写入的字节数。

创建一个管道

  1 #include <unistd.h>
  2 #include <stdio.h>
  3 #include <sys/stat.h>
  4 #include <sys/types.h>
  5 #include <stdlib.h>
  6 int main()
  7 {
  8         int ret=mkfifo("fifo1",0664);
  9         if(ret==-1)
 10         {
 11                 perror("mkfifo");
 12                 exit(0);
 13         }
 14
 15         return 0;
 16 }

接下来我们设计一个微型聊天室:

(1)创建一个具有“写”功能的代码

/*写管道*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
    //1、判断管道是否存在
    int ret=access("test",F_OK);
    if(ret==-1)
    {
        printf("不存在管道,正在创建\n");
        //2、如果管道不存在,,那么接下来需要创建管道
        ret=mkfifo("test",0664);
        if(ret==-1)
        {
            perror("mkfifo");
            exit(0);
        }
    }
   //开始往管道中写数据
    int fd=open("test",O_WRONLY);
    if(fd==-1)
    {
        perror("open");
        exit(0);
    }
    for(int i=0;i<10;i++)
    {
        char buf[1024]={0};
        sprintf(buf,"hello,%d",i);
        printf("send data:%s\n",buf);
        write(fd,buf,strlen(buf));
        sleep(1);//中间休息1秒,要不就太累了
    }
    close(fd);
    return 0;

}

(2)创建一个具有“读”功能的代码

/*读数据*/
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main()
{
    //1、先打开管道,看看里面都给我写的什么东西
    int fd=open("test",O_RDONLY);
    if(fd==-1)
    {
        perror("open");
        exit(0);
    }
    //2、我得把他打印出来,让别人也看看
    while(1)
    {
        char buf[1024]={0};
        int ret=read(fd,buf,sizeof(buf));
        if(ret==0)
        {
            printf("读取失败....");
            exit(0);
        }
        printf("recv:%s\n",buf);
        sleep(1);
    }
    return 0;

}

(3)最后实现的效果为:

 欢迎大家留言交流意见,也希望我们一起完善此文档。

 

举报

相关推荐

0 条评论