user1413824
user1413824

Reputation: 669

Linux commands - abort operation with timeout

I'm writing a script and at some point I call to "command1" which does not stop until it CTRL+C is invoked.

  1. Is there a way to state a timeout for a command? Like: command1 arguments -timeout 10
  2. How do I write a CTRL+C command in textual form?

Thx!

Upvotes: 5

Views: 6175

Answers (3)

atrueresistance
atrueresistance

Reputation: 1368

in your script you can set a wait. wait 10 would wait 10 seconds and as for exiting the program without CTRL + C look into the exit command. If you use exit 0 it means ok. There are different versions, but I don't know what they mean exactly off the top of my head.

exit 1
exit 2..... so on and so forth

Update


@ Celada

No need to bash. You could have just said "maybe you didn't understand the question correctly" Stackoverflow is here to help people learn, not tear them down. They invented Reddit for that. As for the exit codes, you can force the program to exit by issuing the exit() command with a code. Directly from linux.die.net.

Exit Code Number Meaning Example Comments 
1 Catchall for general errors let "var1 = 1/0" Miscellaneous errors, such as "divide by zero" 
2 Misuse of shell builtins (according to Bash documentation)   Seldom seen, usually defaults to exit code 1 
126 Command invoked cannot execute   Permission problem or command is not an executable 
127 "command not found"   Possible problem with $PATH or a typo 
128 Invalid argument to exit exit 3.14159 exit takes only integer args in the range 0 - 255 (see footnote) 
128+n Fatal error signal "n" kill -9 $PPID of script $? returns 137 (128 + 9) 
130 Script terminated by Control-C   Control-C is fatal error signal 2, (130 = 128 + 2, see above) 
255* Exit status out of range exit -1 exit takes only integer args in the range 0 - 255 

Upvotes: -1

betabandido
betabandido

Reputation: 19704

You can use the timeout command from GNU coreutils (you may need to install it first, but it comes in most, if not all, Linux distributions):

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

For instance:

timeout 5 ./test.sh

will terminate the script after 5 seconds of execution. If you want to send a KILL signal (instead of TERM), use -kflag.

Here you have the full description of the timeout command.

Upvotes: 7

Tom Jones
Tom Jones

Reputation: 3

I just tried

jekyll -server & sleep 10;pkill jekyll

Could do for your situation.

Upvotes: 0

Related Questions