Linux, subprocess synchronization

Ok, I need to write code that calls the script, and if the operation in the script hangs, it ends the process.

Python is the preferred language, but I am also looking at the C documentation and the bash script.

Sounds like a light problem, but I can't decide on the best solution.

From research so far:

  • Python: has some weird streaming model that uses a virtual machine one thread at a time won't work?
  • C: The preferred solution seems to use SIGALARM + fork + execl. But SIGALARM is not safe on the heap, so can it destroy everything?
  • Bash: timeout program? Not standard for all distributions?

Since I'm new to Linux, I probably don't know about 500 different gotchas with these features, so can someone tell me what is the safest and cleanest way?

+4
source share
3 answers

In bash, you can do something similar to this:

  • run the script / program in the background with &
  • get the process id of the background process
  • sleep for some time
  • and then kill the process (if it is finished, you cannot kill it), or you can check if the process is alive, and then kill it.

Example:

sh long_time_script.sh & pid=$! sleep 30s kill $pid 

you can even try using trap 'script_stopped $pid' SIGCHLD - see man bash for more information.

UPDATE: I found another timeout command. It does exactly what you need - it runs a command with a time limit. Example:

 timeout 10s sleep 15s 

kill sleep after 10 seconds.

+2
source

Avoid SIGALRM because there are not many safe things inside the signal handler.

Given the system calls you must use in C, after fork-exec is executed to start the subprocess, you can periodically call waitpid(2) with the WNOHANG option to check if the subprocess is working. If waitpid returns 0 (the process is still running) and the desired timeout has passed, you can kill(2) subprocess.

+4
source

There is a collection of Python code that has functions to do just that, and without too much difficulty if you know the API.

The Pycopia collection has a scheduler module for timeout functions and a proctools module for spawning subprocesses and sending signals to it. In this case, you can use the kill method.

+1
source

Source: https://habr.com/ru/post/1369670/


All Articles