go語言獲取發送信號的進程pid

背景

今天在發佈一個程序之前,給qa提測的時候,qa反饋程序運行10幾分鐘之後,退出了

排查過程

在程序中加日誌,發現程序捕獲到了一個SIGTERM信號,然後做了一些退出前的清理工作(在退出之前,該發送的數據還是需要發送的)。然後就需要知道到底是那個進程向我發送SIGTERM信號

代碼

查了一下,貌似go語言沒有直接的發送獲取向自己發送信號的進程的pid,需要嵌入一段c語言代碼,獲取到pid之後,爲了更直觀的知道是那個可執行程序,可以去讀取/proc/${pid}/exe這個軟鏈

package main

/*
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

struct sigaction old_action;
void handler(int signum, siginfo_t *info, void *context) {
    printf("Sent by %d\n", info->si_pid);
    char path[1024];
    char res[1024];
    memset(path, '\0', sizeof(path));
    memset(res, '\0', sizeof(res));
    snprintf(path, sizeof(path), "/proc/%d/exe", info->si_pid);

    if (-1 == readlink(path, res, sizeof(res))) {
        printf("fail to get the symblic link of %s\n", path);
    } else {
        printf("the symblic link of %s is: %s\n", path, res);
    }
}

void test() {
    struct sigaction action;
    sigaction(SIGTERM, 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(SIGTERM, &action, &old_action);
}
*/
import "C"
......
......
func main() {
    ......
    C.test()
    ......
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章