std.process: spawnProcess

viniarck viniarck at gmail.com
Sat Sep 8 11:56:13 UTC 2018


On Friday, 7 September 2018 at 14:36:42 UTC, Russel Winder wrote:
> From what I can see, processes created with std.process: 
> spawnProcess are not terminated when the creating process 
> terminates, i.e. it seems Config.detached is the default for 
> these process.
>
> Is there a way of all spawned processes being terminated on 
> main termination?

On Python std lib, there's a way to daemonize a process [1]. I 
tried to accomplish something equivalent by spawning a process 
inside a daemon thread in D:

```
auto daemonizedProc() {
     import std.process;
     import std.stdio;
     auto pid = spawnProcess(["telnet"]);
     writeln(pid.processID);
}

void main() {
     import core.thread;
     auto t = new Thread(&daemonizedProc);
     t.isDaemon(true);
     t.start();
     // just to see it running for a few secs..
     Thread.sleep(10.seconds);
}
```

Based on my tests, whenever the main process exits (which is 
called "proctest" in the output bellow) the spawned process was 
terminated as a result as well, I tested on Linux:

```
~/repos/dlang master*
❯ ps -ax | egrep "telnet|proctest"
14456 pts/13   S+     0:00 ./proctest
14458 pts/13   S+     0:00 /usr/bin/telnet
14537 pts/7    S+     0:00 grep -E telnet|proctest

~/repos/dlang master*
❯ ps -ax | egrep "telnet|proctest"
14456 pts/13   S+     0:00 ./proctest
14458 pts/13   S+     0:00 /usr/bin/telnet
14633 pts/7    S+     0:00 grep -E telnet|proctest

~/repos/dlang master*
❯ ps -ax | egrep "telnet|proctest"
14731 pts/7    S+     0:00 grep -E telnet|proctest
```

[1] - 
https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process


More information about the Digitalmars-d-learn mailing list