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!