I have an application which needs to do the following:
- If an event happens (a disconnect from server), a long timer is started (say 5 minutes). The application then tries to reconnect to the server.
- If the reconnect fails, a short timer is started (20 seconds) which should attempt to reconnect again.
- If it succeeds, the long timer should keep going.
- When the long timer expires, if there is no connection, the application should exit, otherwise it should continue as normal.
I am limited in that I cannot use threads, only processes. I also cannot afford to wait for the result of reconnect() to return.
So far I have a design like this:
int main(int argc, char **argv)
{
/* do main loop work, if disconnected, call reconnect() & continue doing work */
}
void reconnect()
{
pid = fork();
if (pid >= 0) {
/*Successful fork*/
if (pid == 0) {
rv = attempt_reconnect;
if (rv == 0) {
/*Notify sig_child Success*/
exit(0);
} else {
/*Notify sig_child Fail*/
exit(1);
}
}
}
}
void sig_child(int signum)
{
if(fork returned success) {
set flag to continue network stuff
}
else {
alarm(20);
}
}
void sig_alarm(int signo)
{
/*Received alarm, trying to reconnect...*/
reconnect();
}
Any help would be greatly appreciated!
Edit
I think I have a solution working from an example here. It allows me to create timers with separate ID's, and then identify which one has has signalled the program