Issue
So iam developing a program that when receive a signal kill -SIGUSR1 PID
, need to output to stdout the following line:
2020-10-09T18:01:27+01:00
, and this is the time, when programm was launched, so I need to get this time when the signal is received! I am using siginfo
I dont need to know how to print, I need to know how to get the time when the program was launched!
act.sa_sigaction = signalManagement;
sigemptyset(&act.sa_mask);
act.sa_flags |= SA_SIGINFO;
act.sa_flags |= SA_RESTART;
if (sigaction(SIGUSR1 , &act, NULL) < 0){
ERROR(1, "sigaction - SIGUSR1 ");
}
and my signal function is:
void signalManagement(int sig, siginfo_t *siginfo, void *context)
{
(void)context;
int aux;
aux = errno;
if(sig == SIGUSR1 ){
//* I need code where to show the output "2020-10-09T18:01:27+01:00", example when programm was launched
}
errno = aux;
}
Solution
I need to know how to get the time when the program was launched!
So store the time at your program startup and print it when receiving the signal.
#include <time.h>
#include <stdio.h>
#include <stddef.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
static sig_atomic_t sigusr1_received = 0;
static void sigusr1_handler(int v) {
++sigusr1_received;
}
int main() {
struct tm startuptime = *localtime((time_t[1]){time(0)});
signal(SIGUSR1, sigusr1_handler);
while (1) {
pause();
if (sigusr1_received) {
--sigusr1_received;
char buf[200];
strftime(buf, sizeof(buf), "%FT%X%z", &startuptime);
printf("%s\n", buf);
}
}
}
Adding the additional :
two characters from the back is left as an exerciser to others. One could also call strftime
once at program startup and call write(3)
from signal handler. Like so:
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
static char buf[200];
void sigusr1_handler(int v) {
write(STDOUT_FILENO, buf, strlen(buf));
}
int main() {
strftime(buf, sizeof(buf), "%FT%X%z\n", localtime((time_t[1]){time(0)}));
signal(SIGUSR1, sigusr1_handler);
while (1) {
pause();
}
}
Answered By - KamilCuk