| |
| Posted by Krzysztof Jajeśnica in reply to Alexander Zhirov | PermalinkReply |
|
Krzysztof Jajeśnica
Posted in reply to Alexander Zhirov
| On Monday, 30 May 2022 at 11:18:42 UTC, Alexander Zhirov wrote:
> I want to run a command in the background during the execution of the algorithm, and without waiting for its actual execution, because it is "infinite", while continuing the execution of the algorithm and then, knowing the ID of the previously launched command, kill the process. So far I have done so:
// Here a long program is launched, as an example `sleep`
executeShell("(sleep 10000 && echo \"SLEEP\" >> log) &");
while (!interrupted)
{
// some algorithm is executed here, for example `echo`
executeShell("(echo \"OK\" >> log) &");
if (here is my condition termination of the program)
{
// Here is the termination of the running program
}
Thread.sleep(1.seconds);
}
How to organize such an algorithm correctly?
You could use spawnShell instead of executeShell to spawn the long-running process. spawnShell will return the PID of the spawned process, which you can later use to kill it with the kill function.
import core.stdc.signal : SIGINT;
import std.process;
/* note: with spawnShell you don't need & at the end of command,
because spawnShell doesn't wait for spawned process to complete */
Pid pid = spawnShell("(sleep 10000 && echo \"SLEEP\" >> log)");
while (!interrupted)
{
// some algorithm is executed here, for example `echo`
executeShell("(echo \"OK\" >> log) &");
if (here is my condition termination of the program)
{
/* Kill the previously spawned process using SIGINT signal */
kill(pid, SIGINT);
/* Wait for the killed process to shutdown */
wait(pid);
}
Thread.sleep(1.seconds);
}
|