gpt4 book ai didi

linux - 如何通过在 Jenkins 中使用 bash 脚本读取 pid 文件来终止进程?

转载 作者:太空狗 更新时间:2023-10-29 11:17:16 26 4
gpt4 key购买 nike

Jenkins 中,我必须运行 2 个独立的脚本:start.shstop.sh。这些脚本在我的应用程序中,它是从 SCM 获取的。它们在同一个目录中。

start.sh脚本使用nohup在后台运行一个进程,并将processId写入save_pid.pid。这个脚本工作正常。它成功启动了我的应用程序。

然后在 stop.sh 中,我试图从 save_pid.pid 中读取 processId 以删除进程。但是,我无法删除进程并且应用程序一直运行,直到我使用以下命令手动终止进程:sudo kill {processId}

以下是我目前在 stop.sh 中尝试过的方法,但这些都不起作用:

kill $(cat /path/to/save_pid.pid)

kill `cat /path/to/save_pid.pid`

kill -9 $(cat /path/to/save_pid.pid)

kill -9 `cat /path/to/save_pid.pid`

pkill -F /path/to/save_pid.pid

我也使用 sudo 尝试了所有这些步骤。但是,它就是行不通。我在 stop.sh 中保留了一个 echo 语句,它会打印然后什么也没有。

我在这里做错了什么?

更新:

我在 start.sh 中使用的 nohup 命令是这样的:

nohup deploy_script > $WORKSPACE/app.log 2>&1 & echo $! > $WORKSPACE/save_pid.pid

请注意:

In my case, the value written inside save_pid.pid is surprisingly always less by 1 than the value of actual processId. !!!

最佳答案

我认为发生这种情况的原因是因为您没有获取您感兴趣的进程的 PID,而是获取执行命令的 shell 的 PID .

看:

$ echo "/bin/sleep 10" > /tmp/foo
$ chmod +x /tmp/foo
$ nohup /tmp/foo & echo $!
[1] 26787
26787
nohup: ignoring input and appending output to 'nohup.out'
$ pgrep sleep
26789

所以 'nohup' 将执行 'shell','shell' 将 fork 第二个 'shell' 以执行 'sleep',但是我在这里只能计算两个进程,所以我无法解释创建的进程PID.

请注意,如果您将 nohup 和 pgrep 放在同一行,那么 pgrep 显然会比“exec 的”sleep shell 启动得更快,因此 pgrep 不会产生任何结果,这在某种程度上证实了我的理论:

$ nohup /tmp/foo & echo $! ; pgrep sleep
[2] 26899
nohup: ignoring input and appending output to 'nohup.out'
$

如果您直接启动您的进程,那么 nohup 将“执行”您的进程,从而为该进程保持与 nohup 本身相同的 PID(参见 http://sources.debian.net/src/coreutils/8.23-4/src/nohup.c/#L225):

$ nohup /bin/sleep 10 & echo "$!"; pgrep sleep
[1] 27130
27130
nohup: ignoring input and appending output to 'nohup.out'
27130

此外,如果您在脚本中“执行”“ sleep ”,则只会创建一个进程(正如预期的那样):

$ echo "exec /bin/sleep 10" > /tmp/foo
$ nohup /tmp/foo & echo "$!"; pgrep sleep
[1] 27309
27309
nohup: ignoring input and appending output to 'nohup.out'
27309

因此,根据我的理论,如果您在脚本中“执行”您的进程,那么您将获得正确的 PID。

关于linux - 如何通过在 Jenkins 中使用 bash 脚本读取 pid 文件来终止进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com