How to terminate the execution of a process after some time in Linux

Suppose that you have to execute a Java program which is fairly unstable and sometimes hangs on and never terminates. Is there a simple way to make it terminate (actually by killing the process) after some time? Yes, of course. There is always a way for such things. Ways for everything do not exist though.

So, let's say you have a program.jar to execute but you want to kill its process after 5 minutes in case it does not terminate. A very easy way to do this is the following:

#!/bin/bash

# here you set the time you want to wait before killing the process
time=5m

# then you run your program in the background
java -jar program.jar &

# you are waiting for the time you have set
sleep $time

# some printing - for fun
termination="\nTerminating the process...!!\n"
echo -e $termination

# and now you are about to kill it
kill %1

You can create a script.sh file, just copy paste the code above, and then run the script.sh file (by using the command > sh script.sh).

Lovely

You wonderful, wonderful person!

Terminating process execution

bill's picture

Why? Did you use it ? -:)

Dear I m new and i need help

Dear I m new and i need help in "How to terminate the execution of a process after some time in Linux in C++ ?" thanks in advance

A very obvious answer to

bill's picture
A very obvious answer to this would be applying a timer function inside your source code and brutally use something like Java's System.exit() to terminate the process whenever you want... However, this is not a good way to write code!

Java is so bad language and

Java is so bad language and platform that I never wonder it being used as an example of freezing program ;) Nice to see there is a easy way to kill it for good in linux. Have been administering a linux server this summer and not have to deal this kind of hangups but I'm glad that I found this info so I can bookmark it when needed.

I disagree that Java is a bad

bill's picture

I disagree that Java is a bad programming language :-)

It is really very easy, I

It is really very easy, I have tried it, so I think, that every person can do it.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.