V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
wotemelon
V2EX  ›  Linux

shell 获取进程 id

  •  
  •   wotemelon ·
    wotermelon · 2017-09-27 13:43:46 +08:00 · 3350 次点击
    这是一个创建于 2374 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如何在 shell 中获取上一个执行的进程 id

    # test.sh
    # 想保存运行 xxx.sh 的进程 id,然后保存到文件中
    
    sh ./xxx.sh > /dev/null 2>&1 &
    echo "$!"
    echo "$!" > ./test.pid
    
    

    这样子获取的 $!不准确,正确姿势是什么

    11 条回复    2017-09-27 21:23:17 +08:00
    21grams
        1
    21grams  
       2017-09-27 13:55:12 +08:00 via Android
    echo $$
    nyanyh
        2
    nyanyh  
       2017-09-27 13:55:59 +08:00   ❤️ 1
    $ sh ./1.sh > /dev/null 2>&1 &

    [1] 67891
    [1] + 67891 done sh ./1.sh > /dev/null 2>&1

    echo $!
    67891

    没发现不对的地方啊
    jsfaint
        3
    jsfaint  
       2017-09-27 14:09:45 +08:00
    cat /proc/self/status
    里面有 Pid 一行,就是进程自己的 pid,PPid 是 parents 的 pid
    wotemelon
        4
    wotemelon  
    OP
       2017-09-27 14:16:57 +08:00
    @nyanyh 换个说法,执行了 sh ./xxx.sh 后,xxx.sh 会后台启动一个进程,想把启动的这个进程 id 记录下来 kill,$! 是 sh ./xxx.sh 的 pid,那 xxx.sh 启动的呢?不知道描述的清楚不
    wotemelon
        5
    wotemelon  
    OP
       2017-09-27 14:18:10 +08:00
    @nyanyh 在$!再加 1 就是 xxx.sh 后台启动的 pid,如果直接$! + 1 的话似乎太草率了。。。
    nyanyh
        6
    nyanyh  
       2017-09-27 16:34:23 +08:00
    @wotemelon 那你在 xxx.sh 里执行完进程后面获取$!就可以
    xiaoz
        7
    xiaoz  
       2017-09-27 16:37:03 +08:00
    楼上好复杂啊,直接这样不就获取了:pgrep 'pidname',如 pgrep 'test.pid'
    xiaoz
        8
    xiaoz  
       2017-09-27 16:38:42 +08:00
    Beebird
        9
    Beebird  
       2017-09-27 17:49:27 +08:00
    大概看明白你的需求了,假定 xxx.sh 中只启动一个进程,可以这样:


    sh ./xxx.sh > /dev/null 2>&1 &
    pid_sh=$!
    pid_sh_child=$(pgrep -P $pid_sh)
    echo $pid_sh_child
    echo $pid_sh_child > ./test.pid
    Tink
        10
    Tink  
       2017-09-27 21:11:46 +08:00 via iPhone
    脚本能修改么?能的话直接在脚本里获取进程的 id 保存到文件
    choury
        11
    choury  
       2017-09-27 21:23:17 +08:00
    后台第一个进程就是 %1, 第二个就是%2, 以此类推
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5867 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 02:20 · PVG 10:20 · LAX 19:20 · JFK 22:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.