如何从另一个会话中杀死后台任务?

时间:2013-09-17 12:20:24

标签: linux bash background-process

我在后台运行多线程程序:

./my_task &

然后我退出了,然后再次登录。现在jobs命令不显示此程序,但top确实显示了此程序的线程。所以它仍然在运行。怎么阻止它?我想我可以杀死每个线程,但是有很多线程,我不知道它会如何影响my_task程序。

我正在使用Debian Squeeze。

3 个答案:

答案 0 :(得分:4)

通常情况下,您可以使用

ps aux | grep my_task

- 或者,如果您知道,该进程名称以“my_task”开头:

ps aux | grep [m]y_task

(这将从结果表中排除grep进程本身)

获取所需的流程ID(让它为$pid),然后使用kill $pid

将其删除

编辑(感谢下面的评论):jobsbash本身的一部分,所以有关它的信息列在man bash页面中:

  

作业控制是指有选择地停止(暂停)作业的能力   执行流程并继续          (恢复)他们以后的执行。用户通常通过交互方式使用该设施          由操作系统内核的终端驱动程序和bash共同提供的接口。

   The  shell  associates a job with each pipeline.  It keeps a table of currently executing jobs, which may
   be listed with the jobs command.  When bash starts a job asynchronously (in the background), it prints  a
   line that looks like:

          [1] 25647

   indicating  that  this  job  is  job number 1 and that the process ID of the last process in the pipeline
   associated with this job is 25647.  All of the processes in a single pipeline are  members  of  the  same
   job.  Bash uses the job abstraction as the basis for job control.

但这对案例没有帮助,因为它只列出当前实例的作业(原因是,当你改变你的会话时会改变)

答案 1 :(得分:1)

使用日志运行您的过程。我用gnome-calculator作为例子:

gnome-calculator & echo $! > tmp/11/mylog

并在下面添加.bashrc或其他自动启动来杀死它:

kill `cat tmp/11/mylog`

答案 2 :(得分:1)

您可以使用pgrep查找命令:

$ pgrep my_task
4384

然后你可以使用那个输出来确保它是你想要的命令:

$ ps -fp 4384 | cat

我将输出传递给cat,因为ps命令会切断终端行大小的输出,除非它被传送到另一个命令。

您也可以将它们合并:

$ ps -fp $(pgrep my_task) | cat

如果你勇敢的话,你也可以使用pkill

$ pkill my_task

这将终止与用户拥有的正则表达式my_task匹配的任何进程。