0

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
2
  • 1
    when you launch the app you need to put it into the background using ./app & or else the script will never reach seeing the sleep step until after the app exits Jun 15, 2020 at 11:11
  • I think it's better to use $! to get the PID of app instead of getting it via searching through the process names with pkill. But first you have to put it into background to be able to get it's pid via $!. Jun 15, 2020 at 11:11

2 Answers 2

2

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.

2

You could consider using the timeout command:

NAME
       timeout - run a command with a time limit

SYNOPSIS
       timeout [OPTION] DURATION COMMAND [ARG]...
       timeout [OPTION]

DESCRIPTION
       Start COMMAND, and kill it if still running after DURATION.

ex.

#!/bin/bash

while :
do
  timeout 1h ./app
  sleep 1m
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .