Shell Script kill process

I have a very simple problem: when I run a shell script, I run a program that runs in an infinite loop. After some time, I want to stop this program before I can again with different parameters. The question is, how can I find out the pid when I execute it? Basically, I want to do something like this:

echo "Executing app1 with param1" ./app1 param1 & echo "Executing app1" ..do some other stuff #kill somehow app1 echo "Execution of app1 finished!" 

Thanks!

+7
linux shell
source share
7 answers

In most shells (including Bourne and C), the PID of the last subprocess that you run in the background will be stored in the special variable $ !.

 #!/bin/bash ./app1 & PID=$! # ... kill $PID 

some information here in the section Special variables.

+15
source share

In bash $! expands to the PID of the last process running in the background. So you can do:

 ./app1 param1 & APP1PID=$! # ... kill $APP1PID 
+5
source share

if you want to know the process PID, you can use ps :

 [user@desktop ~]$ ps h -o pid -C app1 

the -o pid parameter says that you only want the PID of the process, -C app1 indicates the name of the process you want to request, and the h parameter is used to suppress the header of the result table (without it, you will see the "PID" header above the PID itself). not so, if there is more than one process with the same name, all PIDs will be shown.

if you want to kill this process, you can use:

 [user@desktop ~]$ kill `ps h -o pid -C app1` 

although killall cleaner if you just want to do it (and if you don't mind killing all the processes of "app1"). you can also use head or tail if you want only the first or last PID, respectively.

and a hint for fish users: %process is replaced by the PID process . so in fish you can use:

 user@desktop ~> kill %app1 
+3
source share

you get pid app1 with

 ps ux | awk '/app1/ && !/awk/ {print $2}' 

and then you can kill him ... (however, if you have multiple instances of application 1, you can kill everything)

+2
source share
 pidof app1 pkill -f app1 
+1
source share
 killall app1 
0
source share

I had a problem where the process I was killing was a python script, and I had another script that also ran python. I did not want to kill python due to another script.

I used awk to solve this problem (let myscript be your python script): kill ps -ef|grep 'python myscript.py'|awk '!/awk/ && !/grep/ {print $2}'

Maybe not as effective, but I would rather trade efficiency for versatility in such a task.

0
source share

All Articles