C after timer_start() sleep is not working - c

I am using eclipse IDE on ubuntu to compile my c project. I have a timer. After starting the timer, sleep or usleep functions are not working.
Here is the code;
EDIT
/*
============================================================================
Name : TimerTest.c
Author : FK
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h> /* , getenv() */
#include <getopt.h>
#include <unistd.h> /* exec(), daemon() */
#include <stdint.h>
#include <string.h> /* memset(), strerror() */
#include <errno.h> /* errno */
#include <libgen.h> /* basename() */
#include <signal.h>
#include <sys/timex.h> /* ntp_gettime() */
#include <time.h>
#include "timer/timer.h"
#define CONFIG_TIMER_INTERVAL 100 /* in ms */
/* global vars decalarations */
static uint8_t _terminate = 0;
static int _signo = 0;
static int init_prg(int argc, char *argv[]);
static void timer_callback(void);
/* function implementations */
static void sig_handler(int signo)
{
/* http://www.yolinux.com/TUTORIALS/C++Signals.html */
_signo = signo;
switch (signo)
{
case SIGINT: /* Program interrupt. (ctrl-c) */
_terminate = 1;
break;
case SIGTERM:
_terminate = 1;
break;
/* SIGKILL, SIGSTOP yakalanımıyor! */
default:
break;
}
}
int main(int argc, char *argv[])
{
init_prg(argc, argv);
/* start super loop */
while (1)
{
printf("test!\n");
//usleep(1000000);
sleep(1);
}
}
static int init_prg(int argc, char *argv[])
{
int res = -1;
if (signal(SIGINT, sig_handler) == SIG_ERR)
{
//exit(EXIT_FAILURE);
}
/* Termination, Generated by "kill" command. */
if (signal(SIGTERM, sig_handler) == SIG_ERR)
{
//exit(EXIT_FAILURE);
}
start_timer(2000, &timer_callback);
if (res != 0)
{
//exit(EXIT_FAILURE);
}
return res;
}
static void timer_callback(void)
{
printf("timer works!\n");
}
after execute program, it echoes "test!" rapidly. Ignoring sleep or usleep commands. if I comment out start_timer line, it sleeps, after timer it is not.Any ideas?

You're not showing what standardized intefaces you're using to start the timer.
Regardless, POSIX specifies that the interaction of usleep with
nanosleep()
setitimer()
timer_create()
timer_delete()
timer_getoverrun()
timer_gettime()
timer_settime()
ualarm()
sleep()
is unspecified.
nanosleep should not have that problem.
From nanosleep's manpage:
Compared to sleep(3) and usleep(3), nanosleep() has the following
advantages: it provides a higher resolution for specifying the sleep
interval; POSIX.1 explicitly specifies that it does not interact with
signals; and it makes the task of resuming a sleep that has been
interrupted by a signal handler easier.
The above suggests that replacing your usleep with:
#include <unistd.h>
int my_usleep(useconds_t Usec);
#include <time.h>
int my_usleep(useconds_t Usec)
{
return nanosleep(&(const struct timespec){
.tv_sec = Usec/100000, .tv_nsec=1000*Usec%1000000}, NULL);
}
should fix the problem.

It seems you are using a timer library similar to the one available at https://www.teuniz.net/Timer_code/ . If you open timer.c in that library, you will see that it uses setitimer(ITIMER_REAL, ...). A timer created in this way will generate a SIGALRM whenever the timer expires. This, in turn, will wake your program from sleep()ing.
Why? Because, if you read the POSIX specification for sleep() (available at http://pubs.opengroup.org/onlinepubs/009695399/ -> Alphabetical index -> sleep()), you will read.
The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.
If, on the other hand, you are not using the afore-mentioned library, then you need to show exactly what your start_timer() function is doing. Otherwise, anyone who tries to help you is shooting in the dark.
Solution: threads
I think your only option is to use separate threads - one thread for the task that sleeps and another for the task that handles the timer.

Related

Setting settimer() and SIGALRM while condition variable is not signaled

I have some practical questions about the settimer() and SIGALRM and how they work .
Let's say that I have some threads created: (EDITED)
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <signal.h>
pthread_mutex_t lock;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void timer_handler (int signum)
{
printf ("\n[WAITING LINE] All our assistants are busy at the moment,we apologize. Please wait on the line\n");
}
void* threadFunc(void* arg){
struct itimerval timer;
if (signal(SIGALRM, (void (*)(int)) timer_handler) == SIG_ERR) {
perror("Unable to catch SIGALRM");
exit(1);
}
timer.it_value.tv_sec =1;
timer.it_value.tv_usec = 0;
while(mycond){
if(setitimer (ITIMER_REAL, &timer, NULL)){
perror("error calling setitimer()");
exit(1);
}
pthread_cond_wait(&cond1,&lock);
//doing other things that take significant time
}
}
int main(){
//initializing mutex
....
//creating the threads
....
//waiting the threads to join
....
return 0;
}
I don't get the message I was supposed to see displayed every 20 msec.
In the example I followed a while(1) was implemented after the settimer but
I can't do that because I want this message displayed while my thread waits for the condition signal.
It doesn't really matter what is implemented in the rest code , let's assume it takes far more time than 20ms to finish and signal the condition.
What should I do to take the timer_handler message every 20ms while the condition is not signaled yet?
I am new to using both condition variables and settimer() so any help to understand them and solve any misunderstaning would be appreciated .
If all your threads are blocked, the virtual timer's clock will not be running.
You might need to switch to ITIMER_REAL. (Also beware that you shouldn't be using async-signal unsafe functions such as printf inside a signal handler.)

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().

Checking to see if signal arrived for given resolution

I have a server and client codes that IPC with each other via named pipes(FIFO). Client sends SIGNAL(SIGUSR1 for example) to Server and checking to see if any signal arrived with given time resolution(via command line argument). Server checks (if its 5ms) 5ms everytime, checks if any signal arrived after 5ms , if arrived it does some code , if not continues until it catches a signal.
So here is that what my problem lies. I dont know what to use for these kind of action. I looked up "Unix Systems Programming: Communication, Concurrency, and Threads Kay A. Robbins , Steven Robbins" found some functions that might be use for me. Sleep,Alarm,uSleep,NanoSleep,Pause. But i dont know which one to use in my situation. Sleep is out of question i think due it takes seconds and i think it overflows when you try to convert to milliseconds.
A little code snippet or psudocode would be nice to understand for me.
I simply asking how to check if signal arrived in given resolution frequency. I have to check if signal arrived in those milliseconds. Check any given "n" mseconds if signal catched.
I think that the function nanosleep (and also usleep) could work!
You have to install a signal handler for the desired signal that can be catched by the program, e.g.:
#include <signal.h>
/* Handler for the signals */
void my_handler(int signum)
{
if(signum == SIGUSR1) {
/* Perform an action on signal SIGUSR1*/
}
}
int main(int argc, char * argv[]){
/* .... */
/* Install the signal handler to catch the desired signals*/
signal(SIGUSR1, my_handler);
/* .... */
}
You have to loop and wait for a signal. And if you catch a signal you have to perform the actions either inside the handler or using the exception that raise when nanosleep is interrupted.
#include <time.h> /* Contains nanosleep + timespec definition */
#include <errno.h> /* Contains the errno variable and the ERROR_CODE macros */
#include <stdio.h> /* Contains definition of perror */
#include <stdlib.h> /* Contains the exit function */
int main(int argc, char * argv[]){
/* fetch milliseconds from argv and put in a variable named "ms" */
struct timespec interval;
interval.tv_sec = 0; /* Seconds*/
interval.tv_nsec = ms*1e6; /* 10^6 Nanoseconds = 1 millisecond */
struct timespec interrupted;
/* .. */
while(1) {
if(nanosleep(&interval, &interrupted) != 0){
/* The sleeping was interrupted! */
if(errno == EINTR){
//The interruption is due to a signal
}
else {
/*The interruption is due to another cause (read the man page) --> Print an error message */
perror("Nanosleep");
break; /* Exit from main loop */
}
}
return EXIT_FAILURE;
}
Alternatively you can also deal the signals inside the handlers.
Alternative Solution
If you are sure that a signal will ever come and don't need to control each 5 milliseconds you could also use the function pause. In fact the man page says:
pause causes the calling process (or thread) to sleep until a signal
is delivered that either terminates the process or causes the
invocation of a signal-catching function.
In this case you have only to install the signal handler and wait.
Let me know if it answered your question.
Sincerly yours,
Mirko

my server doesn't handle all signals when I send it a lot of kill() commands

I have a problem with this little piece of code. I have a "server" and a "client". The server waits SIGUSR1 from the client. But when I send SIGUSR1 in a loop, the server doesn't handle every signal !
I do i++ each time I receive a signal, and I get 981 while I send 1000 signals.
usleep() and sleep() doesn't help.
here is the client code:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int i = 0;
int status = 0;
if (ac < 2)
return (0);
printf("kill %s (%d)", av[1], atoi(av[1]));
for (i=0;i<=1000;i++)
{
printf("%d\n", i);
kill(atoi(av[1]), SIGUSR1);
}
kill(atoi(av[1]), SIGUSR2);
}
and the server code :
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int i = 0;
void sig2(int signum)
{
/* usleep(30); */
printf("%d\n", i);
i = 0;
}
void my_handler(int signum)
{
i++;
}
int main()
{
printf("pid: %d\n", getpid());
if (signal(SIGUSR1, my_handler) == SIG_ERR)
{
printf("rt\n");
exit(0);
}
signal(SIGUSR2, sig2);
while (1);
}
You're missing a few signals that are arriving "on top" of each other, too fast for the application to handle.
The standard says:
If a subsequent occurrence of a pending signal is generated, it is implementation-defined as to whether the signal is delivered or accepted more than once in circumstances other than those in which queuing is required.
... which is a somewhat obscure way of saying that ordinary UNIX signals need not queue. On most implementations, they do not. For example, if five SIGFOO signals are generated before they can be disposed of, only one will be held pending and the application will thus receive only one.
The behavior of signal is not consistent between platforms, on some systems signals are one-shot, on others it's repeating. Linux, specifically, uses System V behavior (unless the _BSD_SOURCE macro is defined) which is one-shot. After a signal have been handled, it resets to SIG_DFL.
To get consistent behavior you should be using sigaction instead where the behavior can be set using flags.

How to wait for time to expire

I would like to have a function run periodically, given a time step. What is the most efficient way to do this?
I know I could use a while look and just keep checking till the dt period has elapsed. But I'd like to know if there is a better, more efficient/elegant function to use.
I was looking into virtual timers and sigaction. Using this method, I would have the sigaction handler set a flag when the time has elapsed, but I would still need to sit in a while loop checking for that flag to be set in my main function. Alternatively I wonder if I could actually have the handler run the function, but then I would have to pass a lot of arguments, and as far as I have read, handlers don't take arguments, so I would have to use lots of global variables.
What would be the best way to tackled this?
On an *IX'ish system you could
install a handler for SIGALRM, which does nothing
set an alarm using alarm()
call blocking pause()
If the alarm signal is sent pause() will return and
you can run the function in question,
again set the alarm
start over calling pause()
#define _POSIX_SOURCE 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
void handler_SIGALRM(int signo)
{
signo = 0; /* Get rid of warning "unused parameter ‘signo’" (in a portable way). */
/* Do nothing. */
}
int main()
{
/* Override SIGALRM's default handler, as the default handler might end the program. */
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler_SIGALRM;
if (-1 == sigaction(SIGALRM, &sa, NULL ))
{
perror("sigaction() failed");
exit(EXIT_FAILURE);
}
}
while (1)
{
alarm(2); /* Set alarm to occur in two seconds. */
pause(); /* The call blocks until a signal is received; in theis case typically SIGARLM. */
/* Do what is to be done every 2 seconds. */
}
return EXIT_SUCCESS;
}
The easiest way is to use sleep or usleep as defined in unistd.h.
If neither of those are available then a common workaround is to use a select with a timeout on no file descriptors.
Include time.h and use sleep function like
#include <time.h>
#include <stdio.h>
#include<windows.h>
#include <conio.h>
int main() {
printf("I am going to wait for 4 sec");
Sleep(4000); //sleep for 4000 microsecond= 4 second
printf("Finaaly the wait is over");
getch();
return 0;
}
It will give you a precise delay on microsecond level.
Hope it helped.

Resources