有名管道总结

      有关无名管道的创建:

       #include

       int mkfifo(const char* pathname,mode_ mode);

       如果是在linux环境下还可以直接在shell终端用mkfifo指令来创建管道文件。

       FIFO常见用途:

      (1)FIFO由shell命令使用以便将数据从一条管道线传送到另一条,为此无需创建中间临时文件。

      (2)FIFO用于客户进程-服务器进程应用程序中,以在客户进程和服务器进程之间传递数据。

        在这里主要讨论第二种用途。(因为第一种用途我也未曾使用过)

       

        先体现用mkfifo创建一个 fifo管道文件,将之作为中转,那么就可以实现两个不相干进程之间的通信了。

        写数据的程序:

 #include
#include
#include
#include
#include
#include


int main(int argc,char* argv[])
{
    int fdw = open("./fifo",O_WRONLY);//以写的形式打开fifo的一端
    char buff[128] = {0};
    while(1)
    {
        printf("请输入\n");
        fgets(buff,128,stdin);


        if(strncmp(buff,"end",3)==0)
        {
             break;
        }
        write(fdw,buff,strlen(buff));//数据被直接写入fifo


    }
    close(fdw);
    return 0;


}


读数据的程序:

#include
#include
#include
#include
#include
#include


int main(int argc,char* argv[])
{
    int fdr = open("./fifo",O_RDONLY);//以读的形式打开fifo
    while(1)
    {
        char buff[128]= {0};
        int n = read(fdr,buff,127);//把fifo里面的数据读到buff上
        if(n==0)
        {
             break;
        }
        printf("get buff = %s",buff);
    }
    fflush(stdout);//ensure print succeed
    close(fdr);
    return 0;
}         













你可能感兴趣的:(有名管道总结)