using select() with pipe

后端 未结 2 1897
滥情空心
滥情空心 2021-02-15 14:19

I am reading/writing to a pipe created by pipe(pipe_fds). So basically with following code, I am reading from that pipe:

fp = fdopen(pipe_         


        
2条回答
  •  太阳男子
    2021-02-15 14:45

    Let's say you wanted to wait 5 seconds and then if nothing was written to the pipe, you print out "dummy."

    fd_set set;
    struct timeval timeout;
    
    /* Initialize the file descriptor set. */
    FD_ZERO(&set);
    FD_SET(pipe_fds[0], &set);
    
    /* Initialize the timeout data structure. */
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
    
    /* In the interest of brevity, I'm using the constant FD_SETSIZE, but a more
       efficient implementation would use the highest fd + 1 instead. In your case
       since you only have a single fd, you can replace FD_SETSIZE with
       pipe_fds[0] + 1 thereby limiting the number of fds the system has to
       iterate over. */
    int ret = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
    
    // a return value of 0 means that the time expired
    // without any acitivity on the file descriptor
    if (ret == 0)
    {
        printf("dummy");
    }
    else if (ret < 0)
    {
        // error occurred
    }
    else
    {
        // there was activity on the file descripor
    }
    

提交回复
热议问题