0

I'm starting a java program by using popen. I want to run a java program for a certain duration and kill it if it's still running after the timeout. I have been using the answer provided here, which is using popen.terminate() and thread.join(). It seems that the python method is ended but the java process is still running. Please help. I'm using Python 2.7.

Community
  • 1
  • 1
Wei Yang
  • 895
  • 3
  • 15
  • 26

1 Answers1

0

If you are using a modern (last 5 years) version of Linux, you should be able to use the timeout command:

Example - this will run for 10 seconds:

$ sleep 10 

This will run for 1 second:

$ timeout 1 sleep 10

Here's an example using this in Python:

p1 = Popen(['timeout' '1' 'sleep' '10'], stdout=PIPE)

You can tell if the program prematurely exited by checking the return code for value 124, otherwise the exit code is that of the java program you ran. There are also other parameters such as the type of kill signal you'd like to send etc. See more by using man timeout.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159