I have a very simple problem: When I run a shell script I start a program which runs in an infinite loop. After a while I wanna stop then this program before I can it again with
In bash $!
expands to the PID of the last process started in the background. So you can do:
./app1 param1 &
APP1PID=$!
# ...
kill $APP1PID
I had a problem where the process I was killing was a python script and I had another script which was also running python. I did not want to kill python because of the other script.
I used awk to deal with this (let myscript be your python script):
kill ps -ef|grep 'python myscript.py'|awk '!/awk/ && !/grep/ {print $2}'
Might not be as efficient but I'd rather trade efficiency for versatility in a task like this.
In most shells (including Bourne and C), the PID of the last subprocess you launched in the background will be stored in the special variable $!.
#!/bin/bash
./app1 &
PID=$!
# ...
kill $PID
There is some information here under the Special Variables section.
killall app1
you obtain the pid of app1 with
ps ux | awk '/app1/ && !/awk/ {print $2}'
and then you should be able to kill it....(however, if you've several instances of app1, you may kill'em all)
if you want to find out the PID of a process, you can use ps
:
[user@desktop ~]$ ps h -o pid -C app1
the parameter -o pid
says that you only want the PID of the process, -C app1
specifies the name of the process you want to query, and the parameter h
is used to suppress the header of the result table (without it, you'd see a "PID" header above the PID itself). not that if there's more than one process with the same name, all the PIDs will be shown.
if you want to kill that process, you might want to use:
[user@desktop ~]$ kill `ps h -o pid -C app1`
although killall
is cleaner if you just want to do that (and if you don't mind killing all "app1" processes). you can also use head
or tail
if you want only the first or last PID, respectively.
and a tip for the fish users: %process
is replaced with the PID of process
. so, in fish, you could use:
user@desktop ~> kill %app1