13

linux如何根据进程pid获取路径

 3 years ago
source link: https://blog.popkx.com/how-linux-gets-the-path-based-on-process-pid/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

linux如何根据进程pid获取路径

发表于 2018-07-31 20:07:47   |   已被 访问: 371 次   |   分类于:   Linux笔记   |   暂无评论

今天遇到这么一个需求,我希望把正在运行的某个进程结束掉,配置了其他环境后,再重新启动该进程。可是,因为不知道该进程在哪,结束掉就不好再启动。想起查看进程资源这一节,类比了一下方法,发现是可行的。


先编写 demo,用 demo 测试更安全,代码如下:

// 文件名:test.c
#include <stdio.h>
#include "stdint.h" 
#include "stdlib.h" 
#include <unistd.h>

int main()
{
    int i = 0;
    while(1){
    sleep(10);
    printf("test is running...\n");
    }
    i = 0;

    return 0;
}

功能很简单,就是每隔 10 秒在终端打印

test is running...

编译并在后台执行:

$ gcc -o test test.c
$ ./test &

根据进程 pid 获取进程所在路径


首先使用 ps 命令查看该进程 pid:

$ ps -A |grep test
 52734 pts/2    00:00:00 test

接着就可以进入进程的资源目录,列出目录文件:

$ cd /proc/52734
$ ls
attr        comm             fd        map_files   net            pagemap      sessionid  status
autogroup   coredump_filter  fdinfo    maps        ns             personality  setgroups  syscall
auxv        cpuset           gid_map   mem         numa_maps      projid_map   smaps      task
cgroup      cwd              io        mountinfo   oom_adj        root         stack      timers
clear_refs  environ          limits    mounts      oom_score      sched        stat       uid_map
cmdline     exe              loginuid  mountstats  oom_score_adj  schedstat    statm      wchan

注意到 exe,它表示进程的运行,它指向存储在磁盘中的进程文件即路径,只需再执行一次 ls -l 命令即可得到进程路径

$ ls exe -l
lrwxrwxrwx 1 lcc lcc 0 7月  31 20:21 exe -> /lccRoot/xx_workPlace/job/7--preAlloStor/5--embed_fat32/build/test

这样就得到了路径:

/lccRoot/xx_workPlace/job/7--preAlloStor/5--embed_fat32/build/test

阅读更多:   Linux笔记


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK