如何获取进程 ID 以杀死 nohup 进程? [英] How to get the process ID to kill a nohup process?

查看:43
本文介绍了如何获取进程 ID 以杀死 nohup 进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在服务器上运行 nohup 进程.当我尝试杀死它时,我的腻子控制台会关闭.

I'm running a nohup process on the server. When I try to kill it my putty console closes instead.

这是我尝试查找进程 ID 的方式:

this is how I try to find the process ID:

ps -ef |grep nohup 

这是杀死命令

 kill -9 1787 787

推荐答案

当使用 nohup 并且你把任务放在后台时,后台操作符 (&)将在命令提示符下为您提供 PID.如果您的计划是手动管理进程,您可以保存该 PID 并在需要时使用它来终止进程,通过 kill PIDkill -9 PID(如果你需要强行杀死).或者,您可以稍后通过 ps -ef | 找到 PID.grep "command name" 并从那里找到 PID.请注意,nohup 关键字/命令本身不会出现在相关命令的 ps 输出中.

When using nohup and you put the task in the background, the background operator (&) will give you the PID at the command prompt. If your plan is to manually manage the process, you can save that PID and use it later to kill the process if needed, via kill PID or kill -9 PID (if you need to force kill). Alternatively, you can find the PID later on by ps -ef | grep "command name" and locate the PID from there. Note that nohup keyword/command itself does not appear in the ps output for the command in question.

如果你使用脚本,你可以在脚本中做这样的事情:

If you use a script, you could do something like this in the script:

nohup my_command > my.log 2>&1 &
echo $! > save_pid.txt

这将运行 my_command 将所有输出保存到 my.log(在脚本中,$! 代表最后执行的进程的 PID).2 是标准错误 (stderr) 的文件描述符,2>&1 告诉 shell 将标准错误输出路由到标准输出(文件描述符 1).它需要 &1 以便 shell 知道它是该上下文中的文件描述符,而不仅仅是名为 1 的文件.2>&1 用于捕获通常写入标准错误的任何错误消息到我们的 my.log 文件(来自标准输出).有关处理 I/O 的更多详细信息,请参阅 I/O 重定向使用 shell 重定向.

This will run my_command saving all output into my.log (in a script, $! represents the PID of the last process executed). The 2 is the file descriptor for standard error (stderr) and 2>&1 tells the shell to route standard error output to the standard output (file descriptor 1). It requires &1 so that the shell knows it's a file descriptor in that context instead of just a file named 1. The 2>&1 is needed to capture any error messages that normally are written to standard error into our my.log file (which is coming from standard output). See I/O Redirection for more details on handling I/O redirection with the shell.

如果命令定期发送输出,您可以偶尔使用tail my.log检查输出,或者如果您想实时"跟踪它你可以使用 tail -f my.log.最后,如果你需要终止进程,你可以通过:

If the command sends output on a regular basis, you can check the output occasionally with tail my.log, or if you want to follow it "live" you can use tail -f my.log. Finally, if you need to kill the process, you can do it via:

kill -9 `cat save_pid.txt`
rm save_pid.txt

这篇关于如何获取进程 ID 以杀死 nohup 进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆