linux C/C++:處理序間通訊-fifo

來源:互聯網
上載者:User

標籤:處理序間通訊   fifo   有名管道   

                          處理序間通訊-fifo

處理序間通訊的另一種方式是fifo。fifo是另一種管道:有名管道。從名字可以看出,它也是隊列。

使用fifo通訊前,得先建立fifo

$ mkfifo myfifo


隨後只需對myfifo像檔案一樣使用就行。

fifo_w.c

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/fcntl.h>struct stu{int id;char name[20];};int main(int argc, char **argv){if(argc != 2){fprintf(stderr, "usage:./app fifo\n");exit(1);}int fd;if((fd = open(argv[1], O_WRONLY)) < 0){fprintf(stderr, "open:can not open file:%s\n", argv[1]);exit(1);}struct stu zx = {0, "zhangxiang"};int id = 0;while(1){id++;zx.id = id;write(fd, &zx, sizeof(zx));sleep(1);}close(fd);return 0;}

fifo_r.c

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/fcntl.h>struct stu{int id;char name[20];};int main(int argc, char **argv){if(argc != 2){fprintf(stderr, "usage:./app fifo");exit(1);}int fd;if((fd = open(argv[1], O_RDONLY)) < 0){fprintf(stderr, "open:can not open file:%s", argv[1]);exit(1);}struct stu zx;while(1){read(fd, &zx, sizeof(zx));printf("id=%d,name=%s\n", zx.id, zx.name);sleep(1);}close(fd);return 0;}


測試

$ gcc fifo_w.c -o fifo_w$ gcc fifo_r.c -o fifo_r$ fifo_w myfifo//另開一終端$ fifo_r myfifoid=1,name=zhangxiangid=2,name=zhangxiangid=3,name=zhangxiangid=4,name=zhangxiangid=5,name=zhangxiangid=6,name=zhangxiangid=7,name=zhangxiangid=8,name=zhangxiang^c 



以上樣本中,一個進程不斷地向fifo中寫入結構體類型的資料,另一個進程不斷地從fifo中讀出資料,從而達到進程間的通訊。



CCPP Blog 目錄


著作權聲明:本文為博主原創文章,轉載,請註明出處。

linux C/C++:處理序間通訊-fifo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.