Friday, May 3, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 831  / 3 Years ago, thu, september 16, 2021, 8:01:45

I have a short script which should launch an app, wait for an hour, then kill it and wait for a minute. It only starts the app. I tried to run the script both as a normal user and root, but nothing helped.


while (true); do
./app
sleep 3600
pkill -f app
sleep 60
done

More From » command-line

 Answers
6

The problem is that all commands are executed from the first line to the last in order. So as @Scott Stensland mentoined you have to put it into background via & (ampersand) to make the timer start.


And furthermore I think getting the PID of your app via searching through process names is a dangerous practice since you might accidentally kill a program which contains the string app in its name. So a safer way is to use the variable ! to get the PID . So your modified script should now looks like this :


while (true); do
./app &
app_pid=$!
sleep 3600
kill $app_pid
sleep 60
done

When you put a process into background via & it goes into the job list of the parent bash process , and via ! you can get the PID of the last job.So it's safe.


[#3204] Thursday, September 16, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rillrage

Total Points: 122
Total Questions: 120
Total Answers: 103

Location: Tokelau
Member since Thu, Aug 26, 2021
3 Years ago
;