Search code examples
csocketsudpudpclientfgetc

Listen on a UDP socket while also receiving input from stdin with C


So I'm trying to make a program in C that can receive packets from another computer via UDP, while also being able to stop listening when someone enters "quit" in the command line. My issue is that both fgets and recvfrom wait until something has happened to move on, so if I'm currently executing fgets my program will ignore incoming messages, and if I'm currently waiting for a message it will ignore input to the terminal. Is there any way I can do both of these at the same time?

Relevant Code:

while (strcmp(sendline, "quit")!=0) {

    fgets(sendline,MAXLINE,stdin);

    if((nbytes=recvfrom(sd,recvline,1+strlen(sendline),0,
        (struct sockaddr*)&sad, &fromlen))<0){
      perror("recvfrom");
      exit(1);
    }  
}

Solution

  • If you switch to using low-level IO (read from fd 0 instead of fread from stdin) you can then use the select() function to be notified of when data is ready on either the fd or socket.