Home >Operation and Maintenance >Linux Operation and Maintenance >Check linux to see if the process exists

Check linux to see if the process exists

(*-*)浩
(*-*)浩Original
2019-12-28 12:00:525441browse

Check linux to see if the process exists

This problem seems to be very simple, just "ps -ef | grep xx" and it will be done! Of course you can do this, but if we consider performance, this may not be a good idea.

Suppose we now want to monitor whether a process is alive and check it every minute. Using the above method, we need to run the ps command every minute and do a grep regular search.

This overhead seems to be nothing on the server, but what if we want to monitor dozens or hundreds of such processes on the same node at the same time? (Recommended learning: linux tutorial)

Therefore, we need to explore some better methods from a performance perspective.

For daemon processes, they usually have their own pid or lock files. We can check whether these files exist to determine whether the process exists. However, under some abnormal circumstances, the process where the pid file exists does not exist. Therefore, you cannot rely on the process's pid file to detect whether the process is alive.

A reliable method is to use "kill -0 pid", kill -0 will not send any signal to the process, but will do error checking. The command returns 0 if the process exists and 1 if it does not exist.

[sw@gentoo ~]$ ps
  PID TTY          TIME CMD
pts/0    00:00:00 bash
pts/0    00:00:00 ps
[sw@gentoo ~]$ kill -0 15091
[sw@gentoo ~]$ echo $?
[sw@gentoo ~]$ kill -0 15092
-bash: kill: (15092) - No such process
[sw@gentoo ~]$ echo $?
[sw@gentoo ~]$

However, this method can only be used for ordinary users to check their own processes, because sending signals to other users' processes will cause an error due to lack of permission, and the return value is also 1.

[sw@gentoo ~]$ kill 2993
-bash: kill: (2993) - Operation not permitted
[sw@gentoo ~]$ echo $?
[sw@gentoo ~]$

Of course, if you use a privileged user to execute the kill command, there will be no permission problem.

The above is the detailed content of Check linux to see if the process exists. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn