Go: Get signal origin

前端 未结 1 363
自闭症患者
自闭症患者 2020-12-16 23:29

I\'m using Go to launch a couple of scripts and when they have some problems they use the \"alert\" signal, I know Go can capture those signals but I need to know the PID th

相关标签:
1条回答
  • 2020-12-17 00:05

    No, you can't do this in an officially supported manner. The Go runtime needs to own the signal handlers, and that extra information isn't exposed in any way.

    You may still be able to do this from C by setting up a new signal handler, but I would be very cautious going about this (see issues like issue/7227). You're probably better off using another method for communication other than a signal.

    Here's a partial example based on Ian's code from issue 7227:

    package main
    
    /*
    #include <stdio.h>
    #include <signal.h>
    #include <string.h>
    
    struct sigaction old_action;
    void handler(int signum, siginfo_t *info, void *context) {
        printf("Sent by %d\n", info->si_pid);
    }
    
    void test() {
        struct sigaction action;
        sigaction(SIGUSR1, NULL, &action);
        memset(&action, 0, sizeof action);
        sigfillset(&action.sa_mask);
        action.sa_sigaction = handler;
        action.sa_flags = SA_NOCLDSTOP | SA_SIGINFO | SA_ONSTACK;
        sigaction(SIGUSR1, &action, &old_action);
    }
    */
    import "C"
    
    import (
        "os"
        "syscall"
        "time"
    )
    
    func main() {
        C.test()
        pid := os.Getpid()
        for {
            syscall.Kill(pid, syscall.SIGUSR1)
            time.Sleep(time.Second)
        }
    }
    
    0 讨论(0)
提交回复
热议问题