获取pid的进程名

Get the process name of pid

相关:
Process name from its pid in linux
Get pid of the process which has triggered some signal

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>

const char* get_process_name_by_pid(const int pid)
{
    char* name = (char*)calloc(1024,sizeof(char));
    if(name){
        sprintf(name, "/proc/%d/cmdline",pid);
        FILE* f = fopen(name,"r");
        if(f){
            size_t size;
            size = fread(name, sizeof(char), 1024, f);
            if(size>0){
                if('\n'==name[size-1])
                    name[size-1]='[=10=]';
            }
            fclose(f);
        }
    }
    return name;
}



static void my_handler(int signum, siginfo_t *siginfo, void *context) {
    printf("Got signal '%d' from process '%d' of user '%d' (%s)\n",
        signum, siginfo->si_pid, siginfo->si_uid, get_process_name_by_pid(siginfo->si_uid));
}

int main(void) {
    struct sigaction act;
    memset(&act, '[=10=]', sizeof(act));
    act.sa_sigaction = &my_handler;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGUSR1, &act, NULL);
    printf("Hi, my pid is %d\ntalk to me with 'kill -SIGUSR1 %d'\n", getpid(), getpid());
    while(1)
        sleep(1000);
    return 0;
}

我正试图找出是谁向程序发送了信号。

这成功显示了信号发送方的 pid,但我还想知道进程名称。

我试过函数 get_process_name_by_pid() 但它似乎不起作用
问题:如何查看进程名称?

我是运行哦 RHEL6.6

您向 get_process_name_by_pid() 函数传递了错误的参数。该函数需要一个进程 ID,您将用户 ID 传递给它。你想要:

get_process_name_by_pid(siginfo->si_pid)