dsmnedc798226 2015-05-13 15:50
浏览 105
已采纳

转到:获取信号来源

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 that originated the Signal. in C to the signal handler is passed a structure to know the pid who originated the signal but in Go looks like is not the case

package main

import (
    "fmt"
    "os"
    "os/signal"
)

func main() {

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, os.Kill)

    s := <-c
    fmt.Println("Got signal:", s)
    fmt.Printf("%+v
",s)
}

the example below (extracted from the signal doc) send me the signal who originated the call but not any useful info (like the pid)

  • 写回答

1条回答 默认 最新

  • douhuibo5635 2015-05-13 22:29
    关注

    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
    ", 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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格