Read-write pipeline as an event notification C ++ implementation

When programming with C ++, often start processing the corresponding task after an event occurs, this approach can be used in Qt signals and slots to be very easy to achieve, but when the server program, you need to do it yourself event notification module.

Here, a write using a pipeline to implement the event notification, the response processing can be achieved for asynchronous events.

  1. Create a pipeline to read and write and add event listeners to epoll

createPipe Boo () 
{ 
     // create a pipe server handles 
    sock_fd = - . 1 ; 

    int pipe_fds [ 2 ] = {- . 1 , - . 1 };
     IF (pipe (pipe_fds) =! 0 ) 
    { 
        return  to false ; 
    } 

    sock_fd          = pipe_fds [ 0 ]; 
    pipe_send_fd      = pipe_fds [ . 1 ]; 

    // nonblocking set 
    int Val = the fcntl (sock_fd, F_GETFL, 0 );
     IF (the fcntl (sock_fd, the F_SETFL, Val | the O_NONBLOCK) == - . 1 ) 
    {
          return  false 
     } 
    // add event listeners to epoll wait epoll_wait return 
}

 

  2. Write data to pipe_send_fd

IF (Write (pipe_send_fd, "" , . 1 )! = . 1 ) // generally after a transmit data queue to notify another thread to process the data in this way the queue

 

  3. epoll_wait returned, and then call the appropriate event handler to receive data

int OnRecv () 
{ 
    char buf [ . 1 ];
     IF (Read (sock_fd, buf, . 1 ) =! . 1 ) 
    { 
        return  0 ; 
    } 

    // get task start processing tasks 
    MsgTask asyn_task;
     IF (! the getMessage (asyn_task)) 
    { 
        return  0 ; 
    } 
    return  . 1 ; 
}

 

Guess you like

Origin www.cnblogs.com/share-ideas/p/10849319.html