Reputation: 47
I have an exercise for which I have to implement a function that takes as parameters a one-parameter function pointer fun
, a parameter to the function pointed at by said pointer parameter
and an integer period
. This function will return either 1 in case the execution of the function fun
points to with parameter
as parameter terminates before period
seconds, or 0 if not.
Are these two solutions equivalent?
static struct sigaction sa, old;
static jmp_buf env;
static void myalarm(int sig)
{
printf("alarm!\n");
siglongjmp(env,1);
}
int execution_time_limit( void (*fun)(void *), void *parameter, int period)
{
sa.sa_handler = myalarm;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGALRM, &sa, &old);
alarm(period);
if(sigsetjmp(env,1) == 0) {
fun(parameter);
sigaction(SIGALRM, &old, NULL);
}
else
return 0;
return 1;
}
And:
static struct sigaction sa, old;
static jmp_buf env;
int ret = 0;
static void myalarm(int sig)
{
printf("alarm!\n");
ret = 1;
}
int execution_time_limit( void (*fun)(void *), void *parameter, int period)
{
sa.sa_handler = myalarm;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGALRM, &sa, &old);
alarm(period);
fun(parameter);
sigaction(SIGALRM, &old, NULL);
return ret;
}
I'd say yes, but I'd like to clear up any doubt I might have.
Upvotes: 0
Views: 303
Reputation: 224102
These are not the same.
In the first example, if the alarm is triggered, fun
does not exit normally due to the call to siglongjmp
. In the second example, the alarm will set the flag for the return value, but fun
will continue to run to completion.
Also, you have a bug here:
if(sigsetjmp(env,1) == 0)
fun(parameter);
sigaction(SIGALRM, &old, NULL);
else
return 0
return 1;
You're missing braces around the if
and else
blocks, and missing the ;
after the first return
. Also I believe you have the return values mixed up based on your description of what the function should do.
The fixed code:
if(sigsetjmp(env,1) == 0) {
fun(parameter);
sigaction(SIGALRM, &old, NULL);
} else {
return 1;
}
return 0;
Upvotes: 1