線程間通信之eventfd

線程間通信之eventfd

man手冊中的解釋:
eventfd()創建了一個“eventfd對象”, 通過它能夠實現用戶態程序間(我覺得這里主要指線程而非進程)的等待/通知機制,以及內核態向用戶態通知的機制(未考證)。
此對象包含了一個被內核所維護的計數(uint64_t), 初始值由initval來決定。


int eventfd(unsigned int initval, int flags);創建一個eventfd文件描述符
int eventfd_read(int fd, eventfd_t *value); 向eventfd中寫入一個值
int eventfd_write(int fd, eventfd_t value); 從eventfd中讀出一個值

例一、子線程多次寫入多個值,主線程一次讀出所有值的和

復制代碼

 1 #include <sys/eventfd.h>2 #include <unistd.h>3 #include <stdlib.h>4 #include <stdio.h>5 #include <stdint.h>  6 7 int main(int argc, char**argv[])8 {9     int efd, j;
10     uint64_t u;
11     ssize_t s;
12     
13     if (argc < 2)
14     {
15         printf("number of argc is wrong!\n");
16         return 0;
17     }
18     
19     efd = eventfd(0,0);
20     if (-1 == efd)
21     {
22         printf("failed to create eventfd\n");
23     }
24     
25     switch(fork())
26     {
27         case 0:
28         {
29             for(j=1; j<argc;j++)
30             {
31                 printf("child writing %s to efd\n", argv[j]);
32                 u = strtoull(argv[j], NULL, 0);
33                 s = write(efd, &u, sizeof(uint64_t));
34                 if (s!=sizeof(uint64_t))
35                 {
36                     printf("write efd failed\n");
37                 }
38             }
39             printf("Child completed write loop\n");
40             exit(0);
41         }
42         default:
43             sleep(2);
44             printf("Parents about to read\n");
45             s = read(efd, &u, sizeof(uint64_t));
46             if (s != sizeof(uint64_t))
47             {
48                 printf("read efd failed\n");
49             }
50             printf("Parents first read %llu (0x%llx) from efd\n", u, u);
51             exit(0);
52         case -1:
53         {
54             printf("fork error\n");
55         }
56     }
57     
58     return 0;
59 }
60 
61 運行結果
62 kane@kanelinux:/mnt/hgfs/kanelinuxshare/eventfd$ ./a.out 1 2 3 4
63 child writing 1 to efd
64 child writing 2 to efd
65 child writing 3 to efd
66 child writing 4 to efd
67 Child completed write loop
68 Parents about to read
69 Parents first read 10 (0xa) from efd
70 
71 如果有寫入操作,但是并沒有導致初始值變化,則主線程會一直掛在read操作上
72 kane@kanelinux:/mnt/hgfs/kanelinuxshare/eventfd$ ./a.out 0 0 0 0
73 child writing 0 to efd
74 child writing 0 to efd
75 child writing 0 to efd
76 child writing 0 to efd
77 Child completed write loop
78 Parents about to read
79 ^C

復制代碼

?

例二、eventfd可以被epoll監控, 一旦有狀態變化,可以觸發通知

復制代碼

  1 #include <sys/eventfd.h>2 #include <unistd.h>3 #include <stdlib.h>4 #include <stdio.h>5 #include <stdint.h>  6 #include <sys/epoll.h>  7 #include <string.h>  8 #include <pthread.h>  9 10 int g_iEvtfd = -1;11 12 void *eventfd_child_Task(void *pArg)13 {14     uint64_t uiWrite = 1;15     16     while(1)17     {18         sleep(2);19         if (0 != eventfd_write(g_iEvtfd, uiWrite))20         {21             printf("child write iEvtfd failed\n");22         }    23     }24 25     return;26 }27 28 int main(int argc, char**argv[])29 {30     int iEvtfd, j;31     uint64_t uiWrite = 1;32     uint64_t uiRead;33     ssize_t s;34     int iEpfd;35     struct epoll_event stEvent;36     int iRet = 0;37     struct epoll_event stEpEvent;38     pthread_t stWthread;39     40     iEpfd = epoll_create(1);41     if (-1 == iEpfd)42     {43         printf("Create epoll failed.\n");44         return 0;45     }46     47     iEvtfd = eventfd(0,0);48     if (-1 == iEvtfd)49     {50         printf("failed to create eventfd\n");51         return 0;52     }53     54     g_iEvtfd = iEvtfd;55     56     memset(&stEvent, 0, sizeof(struct epoll_event));57     stEvent.events = (unsigned long) EPOLLIN;58     stEvent.data.fd = iEvtfd;59     iRet = epoll_ctl(iEpfd, EPOLL_CTL_ADD, g_iEvtfd, &stEvent);60     if (0 != iRet)61     {62         printf("failed to add iEvtfd to epoll\n");63         close(g_iEvtfd);64         close(iEpfd);65         return 0;66     }67     68     iRet = pthread_create(&stWthread, NULL, eventfd_child_Task, NULL);69     if (0 != iRet)70     {71         close(g_iEvtfd);72         close(iEpfd);73         return;74     }75     76     for(;;)77     {78         iRet = epoll_wait(iEpfd, &stEpEvent, 1, -1);79         if (iRet > 0)80         {81             s = eventfd_read(iEvtfd, &uiRead);82             if (s != 0)83             {84                 printf("read iEvtfd failed\n");85                 break;86             }87             printf("Read %llu (0x%llx) from iEvtfd\n", uiRead, uiRead);88         }89     }90     91     close(g_iEvtfd);92     close(iEpfd);93     return 0;94 }95 運行結果96 kane@kanelinux:/mnt/hgfs/kanelinuxshare/eventfd$ ./a.out97 Read 1 (0x1) from iEvtfd98 Read 1 (0x1) from iEvtfd99 Read 1 (0x1) from iEvtfd
100 Read 1 (0x1) from iEvtfd
101 Read 1 (0x1) from iEvtfd
102 Read 1 (0x1) from iEvtfd
103 Read 1 (0x1) from iEvtfd
104 Read 1 (0x1) from iEvtfd
105 ^C

復制代碼

例三、被epoll監控的eventfd,如果在子線程中被多次寫入,在主線程中是怎么讀的?

復制代碼

#include <sys/eventfd.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>  
#include <sys/epoll.h>  
#include <string.h>  
#include <pthread.h>  int g_iEvtfd = -1;void *eventfd_child_Task(void *pArg)
{uint64_t uiWrite = 1;while(1){sleep(2);eventfd_write(g_iEvtfd, uiWrite);eventfd_write(g_iEvtfd, uiWrite);}return;
}int main(int argc, char**argv[])
{int iEvtfd, j;uint64_t uiWrite = 1;uint64_t uiRead;ssize_t s;int iEpfd;struct epoll_event stEvent;int iRet = 0;struct epoll_event stEpEvent;pthread_t stWthread;iEpfd = epoll_create(1);if (-1 == iEpfd){printf("Create epoll failed.\n");return 0;}iEvtfd = eventfd(0,0);if (-1 == iEvtfd){printf("failed to create eventfd\n");return 0;}g_iEvtfd = iEvtfd;memset(&stEvent, 0, sizeof(struct epoll_event));stEvent.events = (unsigned long) EPOLLIN;stEvent.data.fd = iEvtfd;iRet = epoll_ctl(iEpfd, EPOLL_CTL_ADD, g_iEvtfd, &stEvent);if (0 != iRet){printf("failed to add iEvtfd to epoll\n");close(g_iEvtfd);close(iEpfd);return 0;}iRet = pthread_create(&stWthread, NULL, eventfd_child_Task, NULL);if (0 != iRet){close(g_iEvtfd);close(iEpfd);return;}for(;;){iRet = epoll_wait(iEpfd, &stEpEvent, 1, -1);if (iRet > 0){s = eventfd_read(iEvtfd, &uiRead);if (s != 0){printf("read iEvtfd failed\n");break;}printf("Read %llu (0x%llx) from iEvtfd\n", uiRead, uiRead);}}close(g_iEvtfd);close(iEpfd);return 0;
}運行結果:
kane@kanelinux:/mnt/hgfs/kanelinuxshare/eventfd$ ./a.out
Read 1 (0x1) from iEvtfd
Read 1 (0x1) from iEvtfdRead 1 (0x1) from iEvtfd
Read 1 (0x1) from iEvtfdRead 1 (0x1) from iEvtfd
Read 1 (0x1) from iEvtfdRead 1 (0x1) from iEvtfd
Read 1 (0x1) from iEvtfd^C

復制代碼

例一中并沒有epoll做監控,
因此在read前,如果eventfd被寫多次,在read的時候也是一次全部讀出。

?

注:eventfd中的SEMAPHORE標志用法

* If EFD_SEMAPHORE was not specified and the eventfd counter
has a nonzero value, then a read(2) returns 8 bytes contain‐
ing that value, and the counter's value is reset to zero.

* If EFD_SEMAPHORE was specified and the eventfd counter has a
nonzero value, then a read(2) returns 8 bytes containing the
value 1, and the counter's value is decremented by 1.

通過測試發現。如果eventfd在創建的時候傳入EFD_SEMAPHORE 標志,則會按上面man手冊中提到的那樣,每次在eventfd_read的時候只減一,并不是把值一次性全部讀出。見下例 :

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/384983.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/384983.shtml
英文地址,請注明出處:http://en.pswp.cn/news/384983.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【linux 開發】定時器使用setitimer

setitimer Linux 為每一個進程提供了 3 個 setitimer 間隔計時器&#xff1a; ITIMER_REAL&#xff1a;減少實際時間&#xff0c;到期的時候發出 SIGALRM 信號。ITIMER_VIRTUAL&#xff1a;減少有效時間 (進程執行的時間)&#xff0c;產生 SIGVTALRM 信號。ITIMER_PROF&#…

文件操作(寫)

/*** file.c ***/ #include<stdio.h>int main() {//用寫的方式打開一個文件 //w的意思是文件如果不存在&#xff0c;就建立一個文件&#xff0c;如果文件存在就覆蓋FILE *p fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");fputs(&qu…

定時器timerfd

1.為什么要加入此定時器接口 linux2.6.25版本新增了timerfd這個供用戶程序使用的定時接口&#xff0c;這個接口基于文件描述符&#xff0c;當超時事件發生時&#xff0c;該文件描述符就變為可讀。我首次接觸這個新特性是在muduo網絡庫的定時器里看到的&#xff0c;那么新增一個…

文件操作(讀)

讀一行&#xff1a; #include<stdio.h> #include<string.h> #include<stdlib.h> const int maxn 10; int main() {char s[1024] {0};FILE *p fopen("/home/exbot/wangqinghe/C/20190716/file.txt","r");//第一個參數是一個內存地址&…

timerfd與epoll

linux timerfd系列函數總結 網上關于timerfd的文章很多&#xff0c;在這兒歸納總結一下方便以后使用&#xff0c;順便貼出一個timerfd配合epoll使用的簡單例子 一、timerfd系列函數 timerfd是Linux為用戶程序提供的一個定時器接口。這個接口基于文件描述符&#xff0c;通過文…

文件操作(解密加密)

文件加密&#xff1a; #include<stdio.h> #include<string.h> #include<stdlib.h>void code(char *s) {while(*s){(*s);s;} }int main() {char s[1024] {0};FILE *p fopen("/home/exbot/wangqinghe/C/20190716/file.txt","r");FILE *p…

linux僵尸進程產生的原因以及如何避免產生僵尸進程defunct

給進程設置僵尸狀態的目的是維護子進程的信息&#xff0c;以便父進程在以后某個時間獲取。這些信息包括子進程的進程ID、終止狀態以及資源利用信息(CPU時間&#xff0c;內存使用量等等)。如果一個進程終止&#xff0c;而該進程有子進程處于僵尸狀態&#xff0c;那么它的所有僵尸…

linux下僵尸進程(Defunct進程)的產生與避免

在測試基于 DirectFBGstreamer 的視頻聯播系統的一個 Demo 的時候&#xff0c;其中大量使用 system 調用的語句&#xff0c;例如在 menu 代碼中的 system("./play") &#xff0c;而且多次執行&#xff0c;這種情況下&#xff0c;在 ps -ef 列表中出現了大量的 defunc…

文件操作函數

fopen()函數參數&#xff1a; r 只讀的方式打開文件。 打開成功返回文件指針&#xff0c; 打開失敗返回NULL r 以讀寫方式打開文件。 文件必須存在 rb 以二進制模式讀寫文件&#xff0c;文件必須存在 rw 讀寫一個二進制文件&#xff0c;允許讀和寫 w 打開只寫文件&…

讀過的最好的epoll講解

首先我們來定義流的概念&#xff0c;一個流可以是文件&#xff0c;socket&#xff0c;pipe等等可以進行I/O操作的內核對象。 不管是文件&#xff0c;還是套接字&#xff0c;還是管道&#xff0c;我們都可以把他們看作流。 之后我們來討論I/O的操作&#xff0c;通過read&#xf…

文件操作函數(讀寫)

文件文本排序&#xff1a; 數組冒泡&#xff1a; #include<stdio.h>void swap(int *a,int *b) {int temp *a;*a *b;*b temp; }void bubble(int *p,int n) {int i;int j;for(i 0; i < n; i){for(j 1; j < n - i; j){if(p[j - 1] > p[j]){swap(&p[j-1],&…

文件操作(升級)

計算字符串“25 32 ” #include<stdio.h> #include<string.h>int calc_string(char *s) {char buf1[100] {0};char oper 0;char buf2[100] {0};int len strlen(s);int i;for(i 0; i < len; i){if( s[i] || - s[i] || * s[i] || / s[i] ){strncpy…

C語言指針轉換為intptr_t類型

C語言指針轉換為intptr_t類型 1、前言 今天在看代碼時&#xff0c;發現將之一個指針賦值給一個intptr_t類型的變量。由于之前沒有見過intptr_t這樣數據類型&#xff0c;憑感覺認為intptr_t是int類型的指針。感覺很奇怪&#xff0c;為何要將一個指針這樣做呢&#xff1f;如是果…

nginx epoll詳解

nginx epoll 事件模型 nginx做為一個異步高效的事件驅動型web服務器&#xff0c;在linux平臺中當系統支持epoll時nginx默認采用epoll來高效的處理事件。nginx中使用ngx_event_t結構來表示一個事件&#xff0c;先介紹下ngx_event_t結構體中成員的含義&#xff1a; struct ngx_ev…

Inotify機制

描述 Inotify API用于檢測文件系統變化的機制。Inotify可用于檢測單個文件&#xff0c;也可以檢測整個目錄。當檢測的對象是一個目錄的時候&#xff0c;目錄本身和目錄里的內容都會成為檢測的對象。 此種機制的出現的目的是當內核空間發生某種事件之后&#xff0c;可以立即通…

文件操作(二進制文件加密解密)

加密 #include<stdio.h> #include<string.h>void code(char *p,size_t n) {size_t i;for(i 0; i < n; i){p[i] 3;} }int main() {FILE *p1 fopen("./a.txt","r");FILE *p2 fopen("./b.txt","w");char buf[1024] {…

北京加密機現場select問題

問題描述 北京項目通過調用我們提供的庫libsigxt.a與加密機通信&#xff0c;c/s架構&#xff0c;客戶端啟用多個線程&#xff0c;每個線程流程有以下三步&#xff0c;連接加密機&#xff0c;簽名&#xff0c;關閉鏈接。在正常運行一段時間后會出現不能連接加密機服務問題。 連…

拼接字符串(帶參程序)

1.用strcat拼接函數可以實現 #include<stdio.h> #include<string.h>int main(int argc,char ** argv) {char str[100] {0};int i;for( i 1; i < argc; i){strcat(str,argv[i]);}printf("str %s\n",str);return 0; } 2.用sprintf函數也可以實現 #in…

詳細解釋signal和sigaction以及SIG_BLOCK

signal&#xff0c;此函數相對簡單一些&#xff0c;給定一個信號&#xff0c;給出信號處理函數則可&#xff0c;當然&#xff0c;函數簡單&#xff0c;其功能也相對簡單許多&#xff0c;簡單給出個函數例子如下&#xff1a; [cpp] view plain copy 1 #include <signal.h>…

處理SIGCHLD信號

在上一講中&#xff0c;我們使用fork函數得到了一個簡單的并發服務器。然而&#xff0c;這樣的程序有一個問題&#xff0c;就是當子進程終止時&#xff0c;會向父進程發送一個SIGCHLD信號&#xff0c;父進程默認忽略&#xff0c;導致子進程變成一個僵尸進程。僵尸進程一定要處理…