So basically I have 4-5 functions in my program. It is a lot of lines of codes and reading and writing from a file and it could end in an infinite loop (worse case) and I would like to terminate my program if it goes beyond lets say 20 seconds. below code is not working, my program hangs and the OS terminates it for me instead of the program terminating itself. I think the main problem I am having is the alarm is set in the main and when the alarm time limit is reached the process is executing in another function and this is causing the program to shut without closing files and killing child processes. This is what I have for now:
volatile sig_atomic_t keep_going = 1;
/* The signal handler just clears the flag and re-enables itself. */
void
catch_alarm (int sig)
{
printf("Alarm went off");
exit(EXIT_SUCCESS);
}
void function1
{}
void forkingfunction()
{
or(i=0;i<size;i++,temp++)
{
pid_t pID = vfork();
if (pID == 0) // child
{
printf("\nchild pid %d\n",getpid());
//open some files and read and write
function1();
exit(EXIT_SUCCESS);
kill(pID,SIGKILL);
}
}
else if (pID < 0) // failed to fork
{
perror("Failed to fork:");
}
}
void function2
{
function1();
}
int main()
{
int options
while(options){
switch (options)
{
case 1:
case 2:
}
}
signal (SIGALRM, catch_alarm);
alarm (0.1);//testing for 0.1 seconds
function1();
return 0;
}
there is only a certain set of function which can be executed safely from a signal handler. And
exitis not one of them. Neither isprintf.You might able to use the
_exit()function instead (with underscore in front). However it will only exit the top-most process, leaving the children running.You can still kill everything using
kill(0, signal), as here.Here is an example of a working poc code: