信号管理,当发送命令被杀死时

时间:2020-10-09 17:08:01

标签: c linux shell

因此,我要开发一个程序,当接收到信号kill -SIGUSR1 PID时,需要输出以下内容到标准输出:

2020-10-09T18:01:27+01:00,这是启动programm的时间,因此我需要在收到信号时获得该时间!我正在使用siginfo

我不需要知道如何打印,我不需要知道如何启动程序!

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 ");
}

我的信号功能是:

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;
}

2 个答案:

答案 0 :(得分:2)

我需要知道程序启动的时间!

因此,请在程序启动时存储时间,并在收到信号时将其打印出来。

#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);
        }
    }
}

从后面添加另外的:两个字符作为练习者留给其他人。也可以在程序启动时调用一次strftime,然后从信号处理程序中调用write(3)。像这样:

#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();
    }
}

答案 1 :(得分:-3)

您可以这样打印:

printf("2020-10-09T18:01:27+01:00\n");

但是,如果信号处理程序发生在另一个printf调用内,则您正在printf内调用printf,这可能会崩溃。您可以使用write(在Linux上),该方式不能以此方式中断:

const char *message = "2020-10-09T18:01:27+01:00\n";
write(STDOUT_FILENO, message, strlen(message));
相关问题