下面是一些將在Linux上執行的代碼。它沒有stdlib的spawnProcess的所有功能,它只是顯示了基本的基礎知識,但是如果你需要更多的東西,從這裏擴展它並不難。
import core.sys.posix.unistd;
version(linux) {
// this function is Linux-specific
import core.stdc.config;
import core.sys.posix.signal;
// we can tell the kernel to send our child process a signal
// when the parent dies...
extern(C) int prctl(int, c_ulong, c_ulong, c_ulong, c_ulong);
// the constant I pulled out of the C headers
enum PR_SET_PDEATHSIG = 1;
}
pid_t mySpawnProcess(string process) {
if(auto pid = fork()) {
// this branch is the parent, it can return the child pid
// you can:
// import core.sys.posix.sys.wait;
// waitpid(this_ret_value, &status, 0);
// if you want the parent to wait for the child to die
return pid;
} else {
// child
// first, tell it to terminate when the parent dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
// then, exec our process
char*[2] args;
char[255] buffer;
// gotta copy the string into another buffer
// so we zero terminate it and have a C style char**...
buffer[0 .. process.length] = process[];
buffer[process.length] = 0;
args[0] = buffer.ptr;
// then call exec to run the new program
execve(args[0], args.ptr, null);
assert(0); // never reached
}
}
void main() {
mySpawnProcess("/usr/bin/cat");
// parent process sleeps for one second, then exits
usleep(1_000_000);
}
所以下級功能需要使用,但Linux確實有一個功能,做你所需要的。
當然,因爲它發出了一個信號,你的孩子可能要處理,要關閉更優雅比默認的終止,但試試這個程序並運行ps
而它睡覺,看cat
運行,然後注意到貓死時父母退出。
通過同樣的方法,我的意思是'scope(exit){wait(thisProcessID); kill(appPID)...' –
你想讓它強行殺死它們還是讓主程序保持活着直到孩子自然關閉? http://stackoverflow.com/a/23587108/1457000是一個殺的答案(相同的功能可以使用從D ....哦poop你使用高級功能,所以你不能注入該呼叫正確的地方,我需要重新考慮這一點之前發佈作爲答案)。你的等待將不起作用,因爲spawnProcess返回一個魔術類,並且thisProcessId只返回一個int。等待期待班級。但除此之外,等待只對我認爲的孩子,而不是父母... –
嗨,亞當,我不在乎如何接近,但軟性更好。 –