3.2 進程間通訊之fifo

1、引言函數

  FIFO常被稱爲有名管道,不一樣於管道(pipe)。pipe僅適用於「有血緣關係」的IPC。但FIFO還能夠應用於不相關的進程的IPC。實際上,FIFOLinux基礎文件類型中的一種,是在讀寫內核通道。spa

函數原型:命令行

 

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

成功返回 0, 失敗返回 -1

 

命令:code

mkfifo + 管道名   例:mkfifo fifo_oneblog

操做步驟:進程

1) 經過命令行建立fifo;ip

2) 使用open、close、read、write等I/O函數操做fifo原型

2、例程string

1) 建立fifi:it

#mkfifio fifo_one

2) fifo 寫函數

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <sys/stat.h>
 4 #include <sys/types.h>
 5 #include <fcntl.h>
 6 #include <stdlib.h>
 7 #include <string.h>
 8 
 9 void sys_err(char *str)
10 {
11     perror(str);
12     exit(-1);
13 }
14 int main(int argc, char *argv[])
15 {
16     int fd, i;
17     char buf[4096];
18 
19     if (argc < 2) {
20         printf("Please enter: ./a.out fifoname\n");
21         return -1;
22     }
23     fd = open(argv[1], O_WRONLY);//打開fifo
24     if (fd < 0) 
25         sys_err("open");
26 
27     i = 0;
28     while (1) {
       printf("write fifo \n ");
2
sprintf(buf, "hello itcast %d\n", i++); //格式化輸出到buf 31 write(fd, buf, strlen(buf)); //向fifo寫入buf 32 sleep(1); 33 } 34 close(fd); 35 36 return 0; 37 }

3) fifo 讀函數

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <sys/stat.h>
 4 #include <sys/types.h>
 5 #include <fcntl.h>
 6 #include <stdlib.h>
 7 #include <string.h>
 8 
 9 void sys_err(char *str)
10 {
11     perror(str);
12     exit(1);
13 }
14 
15 int main(int argc, char *argv[])
16 {
17     int fd, len;
18     char buf[4096];
19 
20     if (argc < 2) {
21         printf("Please enter: ./a.out fifoname\n");
22         return -1;
23     }
24     fd = open(argv[1], O_RDONLY);//打開fifo
25     if (fd < 0) 
26         sys_err("open");
27     while (1) {
28         len = read(fd, buf, sizeof(buf));//從fifo讀取數據到buf
29         write(STDOUT_FILENO, buf, len); //將buf寫入標準輸出
30         sleep(3);           //多個讀端時應增長睡眠秒數,放大效果.
31     }
32     close(fd);
33     return 0;
34 }

編譯執行:

相關文章
相關標籤/搜索