Linux 如何运行 nohup 并在单个 bash 语句中写入其 pid 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20254155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:29:03  来源:igfitidea点击:

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

linuxbash

提问by amitkarmakar

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

我想在后台运行我的脚本,然后编写它的 pid 文件。我正在使用 nohup 来做到这一点。

This is what i came up with,

这是我想出来的

nohup ./myprogram.sh > /dev/null 2>&1 & && echo $! > run.pid 

But this gives a syntax error.

但这会导致语法错误。

The following doesn't give syntax error but the problem is echo $! doesn't write the correct pid since nohup is run in a sub shell

以下没有给出语法错误,但问题是 echo $! 由于 nohup 在子 shell 中运行,因此没有写入正确的 pid

(nohup ./myprogram.sh > /dev/null 2>&1 &) && echo $! > run.pid 

Any solutions for this, given i want a single line statement for achieving this?

鉴于我想要一个单行语句来实现这一点,有什么解决方案吗?

采纳答案by Grigor Yosifov

You already have one ampersand after the redirect which puts your script in background. Therefore you only need to type the desired command after that ampersand, not prefixed by anything else:

重定向后您已经有一个&符号,它将您的脚本置于后台。因此,您只需要在该与号之后键入所需的命令,而不需要以其他任何前缀:

nohup ./myprogram.sh > /dev/null 2>&1 & echo $! > run.pid

回答by anubhava

This should work:

这应该有效:

nohup ./myprogram.sh > /dev/null 2>&1 &
echo $! > run.pid

回答by Mor Blau

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.

格里戈尔的回答是正确的,但并不完整。直接从 nohup 命令获取 pid 与获取自己进程的 pid 不同。

running ps -ef:

运行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:

要获取您自己的进程的 pid,您可以使用:

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.

请注意,如果您尝试在 nohup 之后立即运行第二个命令,则子进程尚不存在。