內核和用戶空間的消息傳遞-事件通知 (2)

事件通知機制不僅可用戶用戶態兩個線程之間同步,還可以用於內核空間和用戶空間同步。


方法如下:

1.在用戶層

a. 創建一個文件描述符

int event_fd = -1;

event_fd = eventfd ( 0, EFD_NONBLOCK | EFD_SEMAPHORE );


b.將文件描述符通過ioctl傳遞給內核 

enable_message_notification_info.event_fd       = event_fd;

ioctl ( fmb_fd, FMB_API_ENABLE_MESSAGE_NOTIFICATION, &enable_message_notification_info );


c.將事件通知的文件描述符,加入文件描述集,然後用select監控

fd_set read_fds;

while(1)

{

//.將這個文件描述符加入set,然後select監控隊列

FD_ZERO ( &read_fds );
FD_SET ( event_fd , &read_fds );

result = select ( max_fd + 1, &read_fds, NULL, NULL, NULL );

。。。

// 如果有事件觸發

if ( FD_ISSET ( message_thread_param_p->fd_receive_message_notification, &read_fds ) )

 {
  uint32_t message_id;
  uint32_t message_param[FMB_MESSAGE_PARAM_SIZE];

  //清空
  result = eventfd_read ( message_thread_param_p->fd_receive_message_notification, &eventfd_value );
  ASSERT_APP ( result == 0, "ERR: eventfd_read" );

 //事件處理     

 ...  ... 

}

}


2.在內核空間:

a. 通過ioctl得到文件描述符,轉換爲eventfd_ctx

struct eventfd_ctx* eventfd_ctx_p;

eventfd_ctx_p = eventfd_ctx_fdget ( event_fd );


b.在需要發送消息的地方調用以下接口:

eventfd_signal ( queue_p->notification_info.eventfd_ctx_p, 1 );


c.回收這個消息的資源

eventfd_ctx_put ( queue_p->notification_info.eventfd_ctx_p );

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章