Reputation: 3713
What's the best way of executing a command and then killing it after some time? Here's what I have; it does the job, but I get amp: command not found
and although I'm not sure why the amp is there in the first place, I know that the killing doesn't work without it.
feh "$output""$ext" &
echo $!
sleep 1
kill -s 9 $!
exit 1
The thing is that I don't know the PID of the process I'm executing. Could I assign one upon execution?
Upvotes: 3
Views: 4177
Reputation: 2589
GNU timeout, part of recent versions of coreutils, does exactly what you want.
timeout 1 feh "$output""$ext"
runs feh
for one second and then kills it, if it hasn't already ended.
The rest of this comment concerns your current recipe:
The recipe you're currently using puts feh
into the background using the &
. The amp;
after it is a mistake, likely from some overzealous HTML encoder (&
is how you spell &
in HTML).
Every process is assigned a PID by the kernel when launched. $!
is the shell variable for the pid of the most recently backgrounded process.
Upvotes: 7
Reputation: 1655
feh "$output""$ext" &
FEHPID=$!
sleep 1
kill -s 9 $FEHPID
exit 1
Upvotes: 4
Reputation: 1554
You don't want "&" you just want "&". The ampersand tells bash to run the process in the background.
The $! is set to the pid of the background process, so otherwise your sample should do what you want.
Upvotes: 4