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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With