The shell script monitors whether a process has finished running.

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.