原文 我想在执行
算法时,后台运行程序,并要知道程序的pid
来结束它.
executeShell("(sleep 10000 && echo \"SLEEP\" >> log) &");//长期程序
while (!interrupted)
{
//执行算法
executeShell("(echo \"OK\" >> log) &");
if (终止条件)
{
// 终止后台
}
Thread.sleep(1.seconds);
}
最接近的是spawnShell
:
import std.stdio;
import std.process;
import core.thread;
void main() {
auto pid = spawnShell(`(sleep 10000 & echo SLEEP >> log)`);//&&->&来观察
Thread.sleep(5.seconds);kill(pid);
writeln("线程: ", wait(pid));
}
正如std.process
所说,wait()
(等)由平台决定
返回值.
可用spawnShell
而不是executeShell
生成长时间运行
进程.spawnShell
返回生成稍后可用kill
函数干掉的进程的PID
.
import core.stdc.signal : SIGINT;
import std.process;
/* 注意,spawnShell不等待产生进程终止*/
Pid pid = spawnShell("(sleep 10000 && echo \"SLEEP\" >> log)");
while (!interrupted)
{
// 执行算法
executeShell("(echo \"OK\" >> log) &");
if (终止条件)
{
kill(pid, SIGINT);//用信号干掉进程
wait(pid);//等待进程关闭
}
Thread.sleep(1.seconds);
}