Problem description a few days ago, a friend needs to monitor a process in the Linux system in real time. When the program runs, he will continue monitoring. When the program ends, he needs to output a sentence to the terminal, and perform subsequent operations. Problem analysis needs to monitor a process. The latest and first come is the ps command to list all processes and then grep the processes they want, after processing, you can see whether the process is running or has been completed. This method can undoubtedly meet the needs of this problem, but here is a simpler method, you can use the pidof command in Linux to easily monitor the process.
Pidof is used by the pidof process name. If the process exists, the PID of the process is returned. If the process does not exist, null is returned. For example, $ pidof Emacs uses pidof to obtain the process Number of the monitored running process. If the returned value is null, it indicates that the process has ended or is killed, you can proceed to the next step.
Shell code
#! /Bin/shflag = 1 result = 1 while ["$ flag"-EQ 1] do sleep 1 s result = 'pidof top' if [-z "$ result"]; then ECHO "process is finished" flag = 0 fidone # handle the issue ...............
In the code, replace "TOP" with the name of the process to be monitored. "sleep 1 s" takes 1 second to sleep, giving up the CPU. You can select a proper sleep time based on your actual needs. In addition, if the monitored process is a shell script, you need to add the-x option, such as the script of pidof-X.
Summary pidof is a Linux Command that can be used to write process-related scripts that are simpler and more efficient.