killing a process dynamically

Many a times there arises a need to kill a processes without actually being able to type ps on the terminal and look for the process id to give it to kill.
For example this may happen when you write a shell script to run some prerequisite commands and then your application. It may happen that you need to end some mutually exclusive process before starting your application. In this case you can take on of the following two approaches depending on the availability of the commands.

1)  pgrep

    USAGE:    pgrep <application/process name>

    RETURN VALUE: Returns the process id's of all the processes with the specified <process name> as well as those processes whose name contains the <process name>.

    HOW IT WORKS: So if you want to kill some process and want to know its pid, pgrep is exactly what you should use. pgrep returns the application process id which can be given to the kill command in the following way to kill the particular process.

        # pgrep <processs_name> | xargs kill -9

        This will kill all the processes with the process name. But beware before using this command because pgrep also returns process id's of all those processes with <process_name> as a part of their name.

2)  (ps | grep "<process_name>" | cut) series of commands

    USAGE: ps | grep "<application/process_name>" | cut -c(starting nad ending column numbers)

    HOW IT WORKS: This series of commands works with ps which will list all the processes running at that moment. We pipe the output of this command to the grep command. The grep command will take the output of the ps command and search the pattern given as argument. The output of the grep command will contain all the columns of the output of ps command but for only those processes whose name will match. Now to extract only the pid column from all the columns (pid column is the first column in the output of the ps command) we give this output to the cut command. cut command will cut the specific columns given as argument and give as output. So we can cut the first 4 or 5 columns from the output to get the pid ans then give it to the kill command.

        # ps | grep "<process_name>" | cut -c1-5 | xargs kill -9 (You will need to experiment for the column numbers in the cut command on your system.)

No comments:

Post a Comment