简体   繁体   中英

linux C select() never return 0


I have a question with select and pipe. I'm trying to create 3 child processes and each has a pipe to send message to parent process. I'm using select() to check if there is any fd ready. My question is I always get non-zero return value from select() so my loop won't terminate. Can someone help me with this? Thanks.

 int pps[3][3];                                 //pipes
 int highestFD=-1;
 fd_set read_set;
 for (i = 0;i<3;i++) {
   if(pipe(pps[i]) != 0) {
            exit(1);
        }
   int ret= fork();
   if (ret== 0) {
        close(STDOUT_FILENO);
        close(pps[i][0]);
        dup2(pps[i][1], 1);
        write(1, "something", 100);
        exit(0);                               //child process exit
    }
    if (ret > 0) {
        close(pps[i][1]);
        if (pps[i][0] > highestFD)
          highestFD = pps[i][0];
    }
 }

 while(1) {
    FD_ZERO(&read_set);
    for (i = 0;i<3;i++) {
          FD_SET(pps[i][0], &read_set);
    }
    changedCount = 0;
    changedCount = select(highestFD+1, &read_set, NULL, NULL, NULL);
    if (changedCount <= 0) {
         printf("exit");
         break;
    }
    else {
        for (i = 0;i<3;i++) {
         if (FD_ISSET(pps[i][0], &read_set)) {
            int rc = read(pipes[i][0], buffer, 100);
            if (rc > 0) {
               printf("%s\n",buffer);
               memset(buffer, 0, 100);
            }
        }
     }
 }

from the man page for select()

RETURN VALUE
   On success, select() and pselect() return the number of  file  descrip‐
   tors  contained  in  the  three  returned descriptor sets (that is, the
   total number of bits that are  set  in  readfds,  writefds,  exceptfds)
   which  may  be  zero if the timeout expires before anything interesting
   happens.  On error, -1 is returned, and errno is set appropriately; the
   sets  and  timeout  become  undefined, so do not rely on their contents
   after an error.

Notice this statement:

"return the number of file descriptors contained in the three returned descriptor sets"

which (along with the rest of the man page) says

  1. return -1 on error
  2. return 0 if timeout occurs
  3. return >0 when any of the associated fs's have any data movement to report

So, to return a zero, none of the associated fd's can have input any data and an I/O error did not occur.

So why is a 0 never returned from select() in your code?

Answer: because a 0 can only be returned when a timeout occurs and the posted code never setup a timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM