proc.c revision f670eea50e959eeb9da53d70cad8d43c19494ef0
1#include "config.h"
2
3#include <sys/types.h>
4#include <stdio.h>
5#include <string.h>
6#include <signal.h>
7#include <unistd.h>
8
9/* /proc/pid doesn't exist just after the fork, and sometimes `ltrace'
10 * couldn't open it to find the executable.  So it may be necessary to
11 * have a bit delay
12 */
13
14#define	MAX_DELAY	100000	/* 100000 microseconds = 0.1 seconds */
15
16/*
17 * Returns a (malloc'd) file name corresponding to a running pid
18 */
19char *
20pid2name(pid_t pid) {
21	char proc_exe[1024];
22
23	if (!kill(pid, 0)) {
24		int delay = 0;
25
26		sprintf(proc_exe, "/proc/%d/exe", pid);
27
28		while (delay < MAX_DELAY) {
29			if (!access(proc_exe, F_OK)) {
30				return strdup(proc_exe);
31			}
32			delay += 1000;	/* 1 milisecond */
33		}
34	}
35	return NULL;
36}
37