3

什么是查找特定任务的 pid 的最佳和最有效的方法。说:

ps -ef | grep "\/usr\/sbin\/watchdog" | cut -d" " -f2

有没有更有效的方法来找到相同的。我想从我的应用程序中终止看门狗进程。我正在考虑使用系统命令来做同样的事情。

system("kill -9 `ps -ef | grep "\/usr\/sbin\/watchdog" | cut -d" " -f2`);

有没有更优化的方法来做同样的事情。

4

6 回答 6

3

您可以使用pidof

kill -9 `pidof <your application name>`

您的应用程序名称可能是 /usr/sbin/watchdog

于 2011-07-19T09:50:21.180 回答
2

也许这是一个理想的世界解决方案......

要获取看门狗 PID,您只需要打开文件'/var/run/watchdog.pid'.

一旦你知道了一个进程的 PID,最好的杀死进程的方法不是调用'system'函数,而是调用'kill'UNIX API 的函数:

#include <sys/types.h>
#include <signal.h>

int
kill(pid_t pid, int sig);

这样可以避免产生新进程。

如果该文件'/var/run/watchdog.pid'不存在,您可以恢复到 system/kill/pidof。

于 2011-07-20T10:08:24.457 回答
1

要显示当前用户拥有的所有进程,请键入 ps ux 并按回车:

$ ps ux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
jhaas 3064 0.1 3.6 18324 9088 ? S 17:55 0:00 /usr/bin/gnome-session
jhaas 3107 0.0 0.3 3128 968 ? S 17:55 0:00 /usr/bin/ssh-agent /etc/X11/xinit/Xclients
....

现在,如果您想终止例如 emacs 进程,您可以在上表 (3216) 中查找进程标识符 (PID),然后说:

$ kill -9 3216

来源: http: //linux.about.com/library/cmd/blcmdl_kill.htm

于 2011-07-19T09:28:25.967 回答
1

您应该遍历 中的子目录/proc,找到要杀死的进程。然后使用kill(2).

于 2011-07-19T09:29:31.087 回答
1

看看: http: //linux.die.net/man/5/proc

您可以搜索/proc文件系统并找到指向的/proc/$(PIC)/exe链接/usr/sbin/watchdog

一旦你得到 pid 就kill可以了(见 man 2 kill)

于 2011-07-19T09:29:45.350 回答
0

pgrep这实际上非常好,特别是如果您打算使用正则表达式来匹配进程名称。它是procps包的一部分,应该已经安装在任何 linux 系统上(ps在同一个包中)。这是一个示例用法:

psychotic@bismuth ~ $ pgrep 'fire.*'
2902
2903
2904
6979
psychotic@bismuth ~ $ pgrep -l 'fire.*'
2902 firegl
2903 firegl
2904 firegl
6979 firefox-bin
于 2011-07-20T09:31:17.023 回答