bash 如何将pid写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27109364/
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
How do I write pid to file
提问by roy
I know this could be easy, but I am unable to figure out. We want to run two instances of luigi on one machine so need to modify init.d script to write PID to file rather than just touching empty file.
我知道这可能很容易,但我无法弄清楚。我们想在一台机器上运行两个 luigi 实例,所以需要修改 init.d 脚本以将 PID 写入文件而不是仅仅接触空文件。
echo -n $"Starting luigid scheduler as $LUIGID_USER: "
( ( /usr/bin/sudo -u $LUIGID_USER $LUIGID_BIN >>/var/log/luigid/server.log 2>&1 ) &)
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/luigid && echo_success || echo_failure
echo
return $RETVAL
At present its just touching the empty PID file. I want it to write PID into the file. Also while stopping I want to kill by PID stored in PID file
目前它只是触及空的PID文件。我希望它将 PID 写入文件。另外在停止时我想通过存储在 PID 文件中的 PID 杀死
echo -n $"Stopping luigid scheduler: "
killproc luigid
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/luigid && echo_success || echo_failure
echo
Any help please ?
请问有什么帮助吗?
Thanks
谢谢
回答by arco444
You can get the PID
of the previous command with $!
您可以PID
使用$!
Change the start script to:
将启动脚本更改为:
echo -n "Starting luigid scheduler as $LUIGID_USER: "
/usr/bin/sudo -u $LUIGID_USER $LUIGID_BIN >>/var/log/luigid/server.log 2>&1 &
RETVAL=$?
PID=$!
[ $RETVAL -eq 0 ] && echo $PID > /var/lock/subsys/luigid && echo_success || echo_failure
echo
return $RETVAL
Note you need to remove the brackets from around the command as they start the program in a subshell. The subshell will not return the PID of the started program back to your shell, so you should call it directly from your shell.
请注意,当它们在子 shell 中启动程序时,您需要从命令周围删除括号。子shell 不会将启动程序的PID 返回给你的shell,所以你应该直接从你的shell 中调用它。
回答by masseyb
(man
) shlock
should do the trick for that I do believe :
( man
)shlock
应该做到这一点,我相信:
shlock [-du] [-p PID] -f lockfile
...
...
shlock uses the link(2) system call to make the final target lock file, which
is an atomic operation (i.e. "dot locking", so named for this mechanisms
original use for locking system mailboxes). It puts the process ID ("PID")
from the command line into the requested lock file.
Or depending on the situation (man
) flock
, for a great example check this out :
http://codehackit.blogspot.fr/2013/04/locking-processes-with-flock.html
或者根据情况 ( man
) flock
,一个很好的例子看看这个:http:
//codehackit.blogspot.fr/2013/04/locking-processes-with-flock.html