Here's some code I just wrote (yeah, I had time and I tough it was an interesting problem, so I gave it a try; I didn't look for non-blocking IO function but instead I went another way) who ask the user for a number, but will only wait 5 seconds:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
const unsigned int MAX_TIME = 5;
enum
{
OK = 0,
TOO_SLOW
} result;
void sig_handler(int sig_num)
{
if (sig_num == SIGCHLD)
{
result = OK;
}
else if (sig_num == SIGALRM)
{
result = TOO_SLOW;
}
}
int main()
{
pid_t chld_process;
struct sigaction sa;
int shm_id;
void *data;
assert((shm_id = shmget(IPC_PRIVATE, sizeof(int), 0600 | IPC_CREAT)) != -1);
assert((data = shmat(shm_id, NULL, 0)) != (void*) -1);
sa.sa_handler = sig_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
assert(sigaction(SIGALRM, &sa, NULL) != -1);
assert(sigaction(SIGCHLD, &sa, NULL) != -1);
printf("Enter a number: ");
fflush(stdout);
assert((chld_process = fork()) != -1);
if (chld_process == 0)
{
scanf("%d", (int*) data);
shmdt(data);
exit(EXIT_SUCCESS);
}
alarm(MAX_TIME);
pause();
alarm(0);
if (result == OK)
{
printf("Thanks for %d\n", * (int*) data);
}
else
{
kill(chld_process, SIGINT);
printf("\nToo slow... moron.\n");
}
shmdt(data);
return 0;
}
Of course, as you can see, it will only compile on POSIX and mostly-POSIX compliant system. I use only the basic stuff: shared data segments, process creation and signal. You know, this kind of stuff. I didn't put any comments since it's like so easy to understand.