Signal

2020-04-21  本文已影响0人  如果听见下雨的声音

发送信号

#include <iostream>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <memory.h>
#include <fcntl.h>
#include <wait.h>
#include <functional>

void signal_alarm()
{
    alarm(1);

    for (int i = 0;; i++)
        printf("%d\n", i);

}

捕获信号

发送给自己(alarm、reise、abort)
#include <iostream>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <memory.h>
#include <fcntl.h>
#include <wait.h>
#include <functional>

struct SignalHandler
{

    virtual inline void operator()(int sig) const
    {

    }

    static inline void signalHandle(int sig)
    {
        printf("capture signal \n");

        pause();

        printf(" signal handle continue \n ");

    }

};

void capture_signal()
{

//    std::function<void(int)> sh = SignalHandler();

    signal(SIGALRM, SignalHandler::signalHandle);

    alarm(2);

    while (1);

}
发送给指定进程(kill)
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

void sig_kill_with_c()
{

    void (*handle)(int) = [](int sig) -> void
    {
        printf("signal:%s\n", strsignal(sig));

    };

    signal(SIGBUS, handle);

    kill(getpid(), SIGBUS);

}

带参信号(sigqueue)

#include <signal.h>

void sigqueue_with_pure_c()
{
    struct Anim
    {
        char name[20];
        int age;
    };

    struct Anim sigVal{"oneko", 12};

    struct sigaction my_sigaction{};

    sigemptyset(&my_sigaction.sa_mask);

    my_sigaction.sa_flags = SA_SIGINFO;

    my_sigaction.sa_sigaction = [](int sig, siginfo_t *info, void *ucontext) -> void
    {
        struct Anim *revVal = (struct Anim *) info->si_ptr;

        printf("name: %s\narg: %d", revVal->name, revVal->age);

    };

    sigaction(SIGBUS, &my_sigaction, NULL);

    union sigval mysigVal{};

    mysigVal.sival_ptr = &sigVal;

    sigqueue(getpid(), SIGBUS, mysigVal);

}

setitimer

setitimer实现循环定时

#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <wait.h>
#include <csignal>
#include <ctime>
#include <sys/time.h>

void handle_sig (int sig)
{

  struct itimerval val{};

  getitimer (ITIMER_REAL, &val);

  printf ("sec: %ld \t usec: %ld \n", val.it_value.tv_sec, val.it_value.tv_usec);

}

void interval_sig ()
{
  signal (SIGALRM, handle_sig);

  struct itimerval curr{}, old{};
  curr.it_value.tv_sec = 3;
  curr.it_value.tv_usec = 0;
  curr.it_interval.tv_sec = 3;
  curr.it_interval.tv_usec = 0;

  setitimer (ITIMER_REAL, &curr, &old);

}

int main ()
{

  interval_sig ();

  for (;;);

  return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读