c alarm() and pause() causing pause forever - c

In the following program, pause is interrupted once, but then pause never returns. I have set alarm to interrupt pause, so i am confused why pause never returns?
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
static void sig_alrm(int);
static jmp_buf env_alrm;
int main(int arc, char **argv)
{
int x;
x = setjmp(env_alrm);
printf("setjmp was created with return value: %d\n", x);
if(signal(SIGALRM, sig_alrm) == SIG_ERR)
{
printf("Error settting SIGALRM\n");
exit(1);
}
if((x!= 0) && (x!=1))
{
printf("Error setting setjmp\n");
exit(1);
}
printf("Line next to setjmp\n");
x = alarm(2);
printf("Alarm set for 2 seconds, remaning secs from previous alarm: %d\n");
pause();
printf("Line next to pause()\n");
alarm(0);
return 0;
}
static void sig_alrm(int signo)
{
longjmp(env_alrm, 1);
}
Here is the output and the last line shows where the application pauses
setjmp was created with return value: 0
Line next to setjmp
Alarm set for 2 seconds, remaining secs from previous alarm: 0
setjmp was created with return value: 1
Line next to setjmp
Alarm set for 2 seconds, remaining secs from previous alarm: 0

use sigsetjmp() and siglongjmp() instead, to save and restore the signal masks, which are not saved by default in Linux, to clear any pending signals, from man setjmp():
POSIX does not specify whether setjmp() will save the signal mask. In System V it will not.By default, Linux/glibc follows the System V behavior. If you want to portably save and restore signal masks, use sigsetjmp()
and siglongjmp().
Note: I'm not sure what you're trying to accomplish, but your code looks like it's supposed to run in an infinite loop, calling longjmp() restores execution as if it had just returned from setjmp() and it goes on forever.

According to http://linux.die.net/man/2/pause :
pause() only returns when a signal was caught and the signal-catching
function returned.
In your case it never returns, it does the longjmp out.

Related

Catching SIGTERM, and sleep preventing it working

I have some code written in C (working on ubuntu 17):
void sig_stop(int sig_num) {
/* Some cleanup that needs to be done */
}
void some_routine(const char *array[], const int length) {
/* Initialization */
signal(SIGTERM, sig_stop);
while (true) {
/* Some function */
/* I have this sleep to minimize the load on the CPU
as I don't need to check the conditions here
all the time. */
sleep(5);
}
}
Whenever I include the 5 minute sleep (sleep(5)), it appears sig_stop isn't called. However, when I comment out the sleep(5), the sig_stop cleanup works just fine. Have I got something wrong with my understanding of how to catch SIGTERM?
If I can't use the sleep function, is there a better way to "sleep" the program" so that it only runs the loop every x minutes or in such a way that minimizes the CPU load?
sleep() and signals
sleep() should not prevent the signal from being caught and the signal handler being executed. From the manpage for sleep() (emphasis mine):
sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.
Take the following example ...
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
static volatile sig_atomic_t flag = 0;
static void sig_stop(int signum) { flag = 1; }
int main(void) {
int secs_remaining = 0;
signal(SIGTERM, sig_stop);
while (!flag) {
printf("Sleeping at time %d\n", time(NULL));
secs_remaining = sleep(5);
}
printf(
"Flag raised. Exiting at time %d. sleep() was interrupted %d seconds "
"early ...\n",
time(NULL), secs_remaining);
return 0;
}
Note that - in the case where it was interrupted by a signal - sleep() returns the number of seconds left to sleep. E.g., if it is interrupted 3 seconds early it will return 3. It will return 0 if it is not interrupted.
Compile as gcc -o test test.c and run. Then from another terminal run
pkill -15 test
You will see output similar to the following ...
Sleeping at time 1532273709
Flag raised. Exiting at time 1532273711. sleep() was interrupted 2 seconds early ...
By the way ... sleep(x) sleeps for x seconds - not minutes.
signal() vs sigaction()
Due to portability issues associated with signal(), it is often recommended to use sigaction() instead. The use of sigaction() would be something like the following.
int main(void) {
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = sig_stop;
if (sigaction(SIGTERM, &sa, NULL) == -1) {
perror("sigaction");
return 1;
}
// Etc.
}
As you can see the usage of sigaction() is a little more verbose than that of signal(). Perhaps that's why people still sometimes use signal().

Why the signal pause will cause the program to sleep forever?

The APUE book says that: If the signal occurs after the test of sig_int_flag but before the call to pause, the process could go to sleep forever.
I don't know why, can somebody tells me?
Thanks a lot.
int sig_int(); /* my signal handling function */
int sig_int_flag; /* set nonzero when signal occurs */
int main() {
signal(SIGINT, sig_int) /* establish handler */
.
.
.
while (sig_int_flag == 0)
pause(); /* go to sleep, waiting for signal */
}
int sig_int() {
signal(SIGINT, sig_int); /* reestablish handler for next time */
sig_int_flag = 1; /* set flag for main loop to examine */
}
If an interrupt signal is issued at the precise time you're describing:
the flag has been checked false: entering loop
signal resets itself, setting the flag to 1, but too late (test has been done)
since loop has already been entered, pause() is called and the program waits
That said, if CTRL+C/SIGINT is triggered another time, you can exit the loop, so it's not that critical, since that signal can be issued manually.
If you want to check that behaviour, I suggest you add a sleep statement:
while (sig_int_flag == 0)
{
printf("Hit CTRL+C in the next 10 seconds to trigger the bug\n");
sleep(10);
pause(); /* go to sleep, waiting for signal */
}
A workaround would be to remove the pause() statement and replace it by a polling loop:
while (sig_int_flag == 0)
{
sleep(1);
}
If a SIGINT occurs anywhere in the loop, including between the while and the sleep, then the worse thing that can happen is that the program waits 1 second before noticing that the flag is set, then it exits the loop, and the other, more plausible case it that the sleep call is interrupted, and the loop is exited immediately, so when the signal is set, there's little visible difference between that and a pause call if we only expect SIGINT.
The question's already answered. However, additional answer can consolidate the idea.
while (sig_int_flag == 0) {
<----- think it signal is caught here before pause btw while and pause()
pause(); /* go to sleep, waiting for signal */
}
Having caught, signal handler runs. After it finishes its task, it returns to a point at which the signal is caught, in main() in this case. So, the point is pause() and pause() is called. It waits again SIGINT to catch. To exemplify it, I add sleep(5) equivalently to catch prior pause().
So, we typically want the second situation. To achieve it always, the aforementioned code block has to be atomic. That's why sigsuspend() is better and should be used.
If you would like to experience the fallible case,
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
volatile sig_atomic_t sig_int_flag = 0; /* set nonzero when signal occurs */
char const * handlerMsg = "in handler\n";
int handlerMsgLen;
void sig_int(int s) {
signal(SIGINT, sig_int); /* reestablish handler for next time */
sig_int_flag = 1; /* set flag for main loop to examine */
write(2, handlerMsg, handlerMsgLen);
}
void mySleep() {
for (int i = 0; i < 5; ++i) {
sleep(1);
fprintf(stderr, "%d ", i + 1);
}
}
int main() {
handlerMsgLen = strlen(handlerMsg);
signal(SIGINT, sig_int); /* establish handler */
while (sig_int_flag == 0) {
mySleep();
pause(); /* go to sleep, waiting for signal */
}
}

measuring time of signal

I need to measure the time it takes to handle an exception and invoke a signal handler 100,000 times. I need to use signal()system call to register a handler function for SIGFPE then i need to cause a divide by 0 error.
I only have a skeleton right now and am not sure how I should handle the signal. So far I plan on calling gettimeofday() then entering in a for loop 100k times to invoke the signal() then another gettimeofday() in order to end the time and then take the total elapsed time and average it out over those 100k invocations.
#include <signal.h>
#include <sys/time.h>
void handle_sigfe(int signum)
{
//unsure how to handle the signal to keep the loop running for 100k times
}
double time_in_milli (struct timeval t){ //for time conversion
return (((t.tv_sec*1000000+t.tv_usec)*1000)/1000000);
}
int main(int argv, char ** argv)
{
int x =5;
int y = 0;
int z = 0;
signal(SIGFPE, handle_sigfpe);
z = x/y;
return 0;
}
Anyone have any clue on how I need to handle this signal? I am completely lost on this
A divide-by-zero exception invokes the handler that you installed. When the handler returns, the processor goes back to the division instruction and tries again. The result is an infinite loop. To prevent that, you can use the sigsetjmp and siglongjmp routines.
When you call sigsetjmp it returns 0. However, when siglongjmp is called, the program behaves as if sigsetjmp returns the value supplied by siglongjmp. So you can use an if statement to execute the division or skip the division based on the return value from sigsetjmp.
If that's too confusing, hopefully the following example will clear things up.
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
static sig_atomic_t caught = 33;
static sigjmp_buf env;
void action( int unused )
{
caught = 42;
siglongjmp( env, 1 );
}
int main( void )
{
if ( signal( SIGFPE, action ) == SIG_ERR ) {
perror( "signal failed" );
return 1;
}
int x = 1;
int y = 0;
int z;
if ( sigsetjmp( env, 1 ) == 0 )
z = x / y;
printf( "%d\n", caught );
}
The global variable caught is used to indicate that the exception was caught. The initial value is 33. The signal handler sets it to 42. The printf at the end of the program displays the final value. It should print 42 to indicate the that signal was caught.
The global variable env is used by the sigsetjmp and siglongjmp functions to save a copy of the registers and stack.
The if (sigsetjmp(env,1) == 0) will initially be true, and the division will be attempted. But when the handler is invoked, siglongjmp will make the program behave as if sigsetjmp returned 1, and the division will be skipped.
This allows the program to move past the division, and execute the printf at the end.

longjmp,setjmp 's infinite loop

#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
static jmp_buf env_alrm;
static void sig_alarm(int signo)
{
longjmp(env_alrm, 1);
}
int sleep2(unsigned int seconds)
{
if(signal(SIGALRM, sig_alarm)==SIG_ERR)
return seconds;
if(setjmp(env_alrm)==0) //when it is first called, return value is 0
{
alarm(seconds);
pause();
}
return (alarm(0))
}
On this code, I think this is making infinite loop. My thinkings are following:
We call sleep2()functions in main like sleep2(3), then after calling pause(), SIGALRM will be delivered after 3 secs. So, signal handler sig_alarm() will be called.
And, after calling longjmp(), it will go to setjmp() function in sleep2. And finally, after testing setjmp()'s return value(which should be 1 after calling longjmp()) it will execute return alarm(0). So, it will immediately call sig_alarm() again(because SIGALRM is delivered again), and this loop will be continued.
What am I missing?
alarm(0) does not deliver any alarm event. It cancels a previously scheduled alarm and returns the number of seconds remaining until this canceled alarm (if any).
The last line of your code does not cause infinite loop, because it does not execute sig_alarm. It returns the number of seconds remaining to a normal expiration of your sleep2. In your small example this will be zero. Your code is probably a part of larger software where longjmp (and the last line of your sleep2) may be executed before the timer expires. In this case sleep2 returns the number of seconds remaining to a normal expiration.

C: SIGALRM - alarm to display message every second

So I'm trying to call an alarm to display a message "still working.." every second.
I included signal.h.
Outside of my main I have my function: (I never declare/define s for int s)
void display_message(int s); //Function for alarm set up
void display_message(int s) {
printf("copyit: Still working...\n" );
alarm(1); //for every second
signal(SIGALRM, display_message);
}
Then, in my main
while(1)
{
signal(SIGALRM, display_message);
alarm(1); //Alarm signal every second.
That's in there as soon as the loop begins. But the program never outputs the 'still working...' message. What am I doing incorrectly? Thank you, ver much appreciated.
Signal handlers are not supposed to contain "business logic" or make library calls such as printf. See C11 ยง7.1.4/4 and its footnote:
Thus, a signal handler cannot, in general, call standard library functions.
All the signal handler should do is set a flag to be acted upon by non-interrupt code, and unblock a waiting system call. This program runs correctly and does not risk crashing, even if some I/O or other functionality were added:
#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
volatile sig_atomic_t print_flag = false;
void handle_alarm( int sig ) {
print_flag = true;
}
int main() {
signal( SIGALRM, handle_alarm ); // Install handler first,
alarm( 1 ); // before scheduling it to be called.
for (;;) {
sleep( 5 ); // Pretend to do something. Could also be read() or select().
if ( print_flag ) {
printf( "Hello\n" );
print_flag = false;
alarm( 1 ); // Reschedule.
}
}
}
Move the calls to signal and alarm to just before your loop. Calling alarm over and over at high speed keeps resetting the alarm to be in one second from that point, so you never reach the end of that second!
For example:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void display_message(int s) {
printf("copyit: Still working...\n" );
alarm(1); //for every second
signal(SIGALRM, display_message);
}
int main(void) {
signal(SIGALRM, display_message);
alarm(1);
int n = 0;
while (1) {
++n;
}
return 0;
}
Do not call alarm() twice, just call it once in main() to initiate the callback, then once in display_message().
Try this code on Linux (Debian 7.8) :
#include <stdio.h>
#include <signal.h>
void display_message(int s); //Function for alarm set up
void display_message(int s)
{
printf("copyit: Still working...\n" );
alarm(1); //for every second
signal(SIGALRM, display_message);
}
int main()
{
signal(SIGALRM, display_message);
alarm(1); // Initial timeout setting
while (1)
{
pause();
}
}
The result will be the following one :
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
copyit: Still working...
The alarm() call is for a one off signal.
To repeat an alarm, you have to call alarm() again each time the signal occurs.
Another issue, also, is that you're likely to get EINTR errors. Many system functions get interrupted when you receive a signal. This makes for much more complicated programming since many of the OS functions are affected.
In any event, the correct way to wait for the next SIGALRM is to use the pause() function. Something the others have not mentioned (instead they have tight loops, ugly!)
That being said, what you are trying to do would be much easier with a simple sleep() call as in:
// print a message every second (simplified version)
for(;;)
{
printf("My Message\n");
sleep(1);
}
and such a loop could appear in a separate thread. Then you don't need a Unix signal to implement the feat.
Note: The sleep() function is actually implemented using the same timer as the alarm() and it is clearly mentioned that you should not mix both functions in the same code.
sleep(3) may be implemented using SIGALRM; mixing calls to alarm() and sleep(3) is a bad idea.
(From Linux man alarm)
void alarm_handler(int)
{
alarm(1); // recurring alarm
}
int main(int argc, char *argv[])
{
signal(SIGALRM, alarm_handler);
alarm(1);
for(;;)
{
printf("My Message\n");
// ...do other work here if needed...
pause();
}
// not reached (use Ctrl-C to exit)
return 0;
}
You can create variations. For example, if you want the first message to happen after 1 second instead of immediately, move the pause() before the printf().
The "other work" comment supposes that your other work does not take more than 1 second.
It is possible to get the alarm signal on a specific thread if work is required in parallel, however, this can be complicated if any other timers are required (i.e. you can't easily share the alarm() timer with other functions.)
P.S. as mentioned by others, doing your printf() inside the signal handler is not a good idea at all.
There is another version where the alarm() is reset inside main() and the first message appears after one second and the loop runs for 60 seconds (1 minute):
void alarm_handler(int)
{
}
int main(int argc, char *argv[])
{
signal(SIGALRM, alarm_handler);
for(int seconds(0); seconds < 60; ++seconds)
{
alarm(1);
// ...do other work here if needed...
pause();
printf("My Message\n");
}
// reached after 1 minute
return 0;
}
Note that with this method, the time when the message will be printed is going to be skewed. The time to print your message is added to the clock before you restart the alarm... so it is always going to be a little over 1 second between each call. The other loop is better in that respect but it still is skewed. For a perfect (much better) timer, the poll() function is much better as you can specify when to wake up next. poll() can be used just and only with a timer. My Snap library uses that capability (look for the run() function, near the bottom of the file). In 2019. I moved that one .cpp file to the eventdispatcher library. The run() function is in the communicator.cpp file.
POSIX permits certain of its functions to be called from signal handling context, the async-signal safe functions, search for "async-sgnal safe" here. (These may be understood as "system calls" rather than library calls). Notably, this includes write(2).
So you could do
void
display_message (int s) {
static char const working_message [] = "copyit: Still working...\n";
write (1, working_message, sizeof working_message - sizeof "");
alarm(1); /* for every second */
}
By the way, precise periodic alarms are better implemented using setitimer(2),
since these will not be subject to drift. Retriggering the alarm via software, as done here, will unavoidably accumulate error over time because of the time spent executing the software as well as scheduling latencies.
In POSIX sigaction(2) superceedes signal(2) for good reason:
the original Unix signal handling model was simple. In particular,
a signal handler was reset to its original "deposition" (e.g., terminate
the process) once it was fired. You would have to re-associate
SIGALRM with display_message() by calling signal() just before
calling alarm() in display_message().
An even more important reason for using sigaction(2) is the
SA_RESTART flag. Normally, system calls are interrupted when
a signal handler is invoked. I.e., when then signal handler returns,
the system call returns an error indication (often -1) and errno is
set to EINTR, interrupted system call. (One reason for this
is to be able to use SIGALRM to effect time outs, another is
to have a higher instance, such as a user, to "unblock" the
current process by sending it a signal, e.g.,
SIGINT by pressing control-C at the terminal).
In your case, you want signal handling to be transparent
to the rest of the code, so you would set the SA_RESTART flag
when invoking sigaction(2). This means the kernel should
restart the interrupted system call automatically.
ooga is correct that you keep reloading the alarm so that it will never go off. This works. I just put a sleep in here so you don't keep stepping on yourself in the loop but you might want to substitute something more useful depending on where you are headed with this.
void display_message(int s)
{
printf("copyit: Still working...\n" );
// alarm(1); //for every second
// signal(SIGALRM, display_message);
}
int main(int argc, char *argv[])
{
int ret;
while(1)
{
signal(SIGALRM, display_message);
alarm(1);
if ((ret = sleep(3)) != 0)
{
printf("sleep was interrupted by SIGALRM\n");
}
}
return (0);
}

Resources