How to run nohup and write its pid file in a single bash statement

后端 未结 3 1665
刺人心
刺人心 2021-01-30 08:26

I want to run my script in background and then write its pid file. I am using nohup to do this.

This is what i came up with,

nohup ./myprogram.sh > /d         


        
3条回答
  •  忘掉有多难
    2021-01-30 08:58

    Grigor's answer is correct, but not complete. Getting the pid directly from the nohup command is not the same as getting the pid of your own process.

    running ps -ef:

    root     31885 27974  0 12:36 pts/2    00:00:00 sudo nohup ./myprogram.sh
    root     31886 31885 25 12:36 pts/2    00:01:39 /path/to/myprogram.sh
    

    To get the pid of your own process, you can use:

    nohup ./myprogram.sh > /dev/null 2>&1 & echo $! > run.pid
    # allow for a moment to pass
    cat run.pid | pgrep -P $!
    

    Note that if you try to run the second command immediately after nohup, the child process will not exist yet.

提交回复
热议问题