linux进程可执行文件的绝对路径
这种情况很少遇到,我们需要一个运行中进程的绝对路径,可惜的是glibc中或者系统调用中我都没有找到类似的函数。但是linux绝对不会不给你这个机会的,那就是proc文件系统了。在proc文件系统中那些数字都是运行中的进程,进入一个文件名为数字的文件夹以后,我们就可以发现以下类似文件目录结构。
[cyher@cyher ~]$ ls /proc/3355/ attr cpuset io mountinfo pagemap smaps task auxv cwd latency mounts personality stack wchan cgroup environ limits mountstats root stat clear_refs exe loginuid net sched statm cmdline fd maps oom_adj schedstat status coredump_filter fdinfo mem oom_score sessionid syscall
这里就是一个进程所有的信息了大名鼎鼎的ps命令就是读取这里的内容解析出信息的,这里是ps的官方网站 http://procps.sourceforge.net/
那好了,就用这里给的信息来解析出执行文件的绝对路径吧
/* * ===================================================================================== * * Filename: get_exe_path.c * * Description: * * Version: 1.0 * Created: 2009年09月23日 17时07分17秒 * Revision: none * Compiler: gcc * * Author: cyher (), cyher.net@gmail.com * Company: cyher.net * * ===================================================================================== */ #include #include #include #define BUF 128 int main(int agrc, char **argv) { char buf[BUF]; char proc[BUF]; char *p; sprintf(proc, "/proc/%d/exe", atoi(argv[1])); readlink(proc,buf, BUF); /*proc/pid/exe 是一个链接,用readlink读*/ p = strchr(buf,'('); /*读出的路径后面有可能会有 (deleted)字样,删去*/ if (p != NULL) { p--; *p = '\0'; } puts(buf); }
这样就能读取出绝对路径了,不过你首先要知道pid啊 呵呵。