Linux一個命名管道_Linux教程

      編輯Tag賺U幣

         命名管道也是按照文件操作流程進行的,可以看做特殊文件。

        寫管道進程:打開-寫-關閉

        讀管道進程:打開-讀-關閉

        本實驗采用阻塞式讀寫管道,一個程序寫,另一個讀。

         寫:

        #include<sys/types.h>

        #include<sys/stat.h>

        #include<errno.h>

        #include<fcntl.h>

        #include<stdio.h>

        #include<stdlib.h>

        #include<limits.h>

        #define MYFIFO  "/tmp/myfifo"

        #define MAX_BUFFER_SIZE     PIPE_BUF

        int main(int argc, char* argv[])

        {

        char buff[MAX_BUFFER_SIZE];

        int fd;

        int nwrite;

        if(argc <= 1)

        {

        printf("usage: ./write string!\n");

        exit(1);

        }

        sscanf(argv[1], "%s", buff);

        fd = open(MYFIFO, O_WRONLY);//打開管道,寫阻塞方式

        if(fd == -1)

        {

        printf("open fifo file error!\n");

        exit(1);

        }

        if((nwrite = write(fd, buff, MAX_BUFFER_SIZE)) > 0)//寫管道

        {

        printf("write '%s' to FIFO!\n ", buff);

        }

        close(fd);//關閉

        exit(0);

        }

        讀:

        #include<sys/types.h>

        #include<sys/stat.h>

        #include<errno.h>

        #include<fcntl.h>

        #include<stdio.h>

        #include<stdlib.h>

        #include<limits.h>

        #define MYFIFO  "/tmp/myfifo"

        #define MAX_BUFFER_SIZE     PIPE_BUF

        int main()

        {

        char buff[MAX_BUFFER_SIZE];

        int fd;

        int nread;

        //判斷管道是否存在,如果不存在則創建

        if(access(MYFIFO, F_OK) == -1)

        {

        if((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST))

        {

        printf("cannot creat fifo file!\n");

        exit(1);

        }

        }

        fd = open(MYFIFO, O_RDONLY);//打開管道,只讀阻塞方式

        if(fd == -1)

        {

        printf("open fifo file error!\n");

        exit(1);

        }

        while(1)

        {

        memset(buff, 0, sizeof(buff));

        if((nread = read(fd, buff, MAX_BUFFER_SIZE)) > 0)//讀管道

        {

        printf("read '%s' from FIFO\n", buff);

        }

        }

        close(fd);//關閉

        exit(0);

        }

        編譯運行,打開兩個終端,一個寫,一個讀。

       

      來源:網絡搜集//所屬分類:Linux教程/更新時間:2011-12-08
      相關Linux教程