Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a command after x seconds without using timeout [duplicate]

Tags:

linux

bash

kill

I'm trying to execute a command for an x amount of seconds and then stop it afterwards. I guess normally you'd do this with the timeout command, but this program does not seem to be available on my machine, so I'm trying to still get this to work a different way.

Here's one of the commands I've tried:

./some_program & sleep 5; kill `pidof some_program`

Normally when I manually interrupt some_program using ctrl+c, it generates a csv file of the results, but the above command just seems to stop it, and there is no csv file that is created. If I use kill -9, it will terminate the program, but again, no csv file will be generated.

How can I automatically stop the program after an x number of seconds and still cause it to generate the csv file? (I've tried kill -2, kill -3 andkill -15.)

like image 873
user2548144 Avatar asked Dec 12 '25 01:12

user2548144


1 Answers

To get the same effect as C-c (assuming the program doesn't change tty settings to handle it in a non-standard way), you'll want to send SIGINT. Also, avoid running pidof - bash gives you the last background job as %+ when you use kill.

You should be able to

./some_program & sleep 5; kill -INT %+

Demonstration

$ time bash -c 'sleep 15 & sleep 3; kill -INT %+'

real    0m3.005s
user    0m0.001s
sys     0m0.004s
like image 105
Toby Speight Avatar answered Dec 14 '25 15:12

Toby Speight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!