相关:
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]='\0';
}
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, '\0', 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
答案 0 :(得分:4)
您将错误的参数传递给get_process_name_by_pid()函数。该函数需要一个进程ID,您将其传递给用户ID。你想要:
get_process_name_by_pid(siginfo->si_pid)