c - using select to read from socket and stdin -


i'm writing ncurses based chat program. @ first, wrote networking stuff (without ncurses) , worked fine, after adding graphics can't client app work properly.

the main problem reading stdin , socket @ same time. in ncurses-less version i've used pthread , worked charm. alas, seems pthread , ncurses don't go well, had find solution. thought select() do, still reads stdin , ignores socket.

here whole code: code

the interesting part is:

char message[1024]; fd_set master; fd_set read_fds;  fd_zero(&master); fd_zero(&read_fds);  fd_set(0,&master); fd_set(s,&master); // s socket descriptor while(true){ read_fds = master; if (select(2,&read_fds,null,null,null) == -1){   perror("select:");   exit(1); } // if there data ready read socket if (fd_isset(s, &read_fds)){   n = read(s,buf,max);   buf[n]=0;   if(n<0)   {     printf("blad odczytu z gniazdka");     exit(1);   }    mvwprintw(output_window,1,1,"%s\n",buf); } // if there in stdin if (fd_isset(0, &read_fds)){   getstr(message);   move(curs_y++,curs_x);   if (curs_y == lines-2){     curs_y = 1;   }   n = write(s,message,strlen(message));   if (n < 0){     perror("writethread:");     exit(1);   } } } 

it's possible don't understand how select() works, or maybe shouldn't have connect()ed socket.. i'm lost here. appreciate help! thanks.

your problem in select().
first parameter not number of file descriptors passing in read_fds, it's highest socket id + 1.

from man page:

the first nfds descriptors checked in each set; i.e., descriptors 0 through nfds-1 in descriptor sets examined. (example: if have set 2 file descriptors "4" , "17", nfds should not "2", rather "17 + 1" or "18".)

so in code, instead of '2', try passing 's+1'.


Comments