/* Well, in case you don't know, the halting problem's actually unsolvable. But next time you're calling a blocking function in C, and you don't have the source code for that darn function, and you need it to be nonblocking because sometimes it doesn't work and freezes up (can you tell this happened to us?), then you can use this example code to spawn a new process, try the function in the child process, and kill it if it freezes up. Enjoy. */ #include #include #include #include int failsafe(); main() { int retval; printf("Welcome. Calling failsafe()...\n"); retval = failsafe(); printf("failsafe returned: %d\n", retval); } int failsafe() { pid_t pid; int fildes[2]; char data[25]; int failcase; /* make a pipe for inter-process communication */ pipe(fildes); /* make the pipe non-blocking! */ fcntl(fildes[0], F_SETFL, O_NONBLOCK); fcntl(fildes[1], F_SETFL, O_NONBLOCK); pid = fork(); if (pid == 0) { /* This is the child process! */ printf("I am the child! Hi!\n"); /* Do the dangerous failure-prone thing HERE */ /* the next line goes AFTER the dangerous call */ printf("child:Success:Writing now...\n"); write(fildes[1], "done", sizeof("done")); sleep(5); /* Giving parent time to see result */ printf("Child: exiting now.\n"); exit(0); } else { /* This is the parent process! */ failcase = 0; printf("I am the parent!\n"); sleep(1); /* Give time here for child to succeed */ /* Seb, if you make the sleep(1) above a sleep(0), then the child won't have "time" to write 'done' and the parent will kill it. This simulates a sonar freeze */ failcase = read(fildes[0], data, 3); /* read returns either a 3 (if the child is still alive) or a -1 (if nothing exists on the pipe to be read) */ printf("Parent: Read returned %d\n",failcase); if (failcase == -1) { /* Kill the child here!!! fail case! */ kill(pid,SIGKILL); return -1; } else { /* Success case; child will commit suicide. */ /* But we kill child here anyway, just for symmetry */ kill(pid,SIGKILL); return 1; } /* end else success case */ } /* end else (parent case) */ } /* end failsafe() */