Problem description
A few days ago, a friend needs real-time monitoring of a Linux system under a process, when the program is running to continue to monitor, when the program is finished to the end of a word to the end, and do follow-up.
Problem analysis
To monitor a process, the newest first to go is the PS command that lists all the processes and then grep the process you want, so that the process can be processed to see if it is running or has ended. This approach can undoubtedly achieve this problem, but there are simpler ways to use the PIDOF command in Linux systems to simply implement monitoring of the process.
Pidof is used in the following way: Pidof process name. If the process exists, the PID number of the process is returned and null if it does not exist. Example: $ pidof emacs
Thus, using pidof to get the process number of the running process being monitored, if the resulting return value is NULL, the process is closed or killed, and the next step can be taken.
Shell Code
#!/bin/sh
flag=1
result=1 while
["$flag"-eq 1] does sleep
1s
result= ' pidof top '
if [-Z ' $ Result "]; Then
echo "process is finished"
flag=0
fi
do the appropriate processing ........
The top of the code is replaced by the name of the process to monitor, sleep 1s is 1 seconds, to give up the CPU, you can choose the right time according to the actual needs of sleep. Also, if the process being monitored is a shell script, you need to add the-X option, such as pidof-x the corresponding script.
Summary
Pidof is a Linux command that can use its features to write simpler, more efficient process-related scripts.