Avoid multiprocess and multi-threaded programming if you can. That road leads to pain. Use event driven programming. For the type of thing you are wanting to do, event driven programming is much easier, and will perform just as well. The two main ways in C to do event driven programming (related to I/O) are select
and poll
.
Here is working example of using select:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval, len;
char buf[4096];
while (1) {
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1) {
perror("select()");
exit(EIO);
} else if (retval) {
printf("Data is available now.\n");
} else {
printf("No data within five seconds.\n");
continue;
}
if (FD_ISSET(0, &rfds)) {
len = read(0, buf, 4096);
if (len > 0) {
buf[len] = 0;
printf("Got data on stdin: %s\n", buf);
} else {
// fd closed
perror("read()");
exit(EIO);
}
}
}
}
FD_SET is used to create the list of file-descriptors you want to select on (get events from). After select returns successfully (meaning there is an event to process), you use FD_ISSET to find the file-descriptors that caused events. In your case you are going to have an open socket file-descriptor that you will add to the set and process appropriately.
Useful documentation include the following man pages:
man 2 select
man 2 poll
man 3 read
man 3 open