我想通过停止事件循环来正常关闭vibe.d应用程序。
source_urls
不幸的是,这不起作用:
import vibe.vibe;
import core.sys.posix.signal;
void main()
{
enum SIGINT = 2;
signal(SIGINT, &stopapp);
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, &hello);
logInfo("Please open http://127.0.0.1:8080/ in your browser.");
runApplication();
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody("Hello, World!");
}
void stopapp(int value){
logInfo("Stopping app...");
exitEventLoop();
}
有一个简单的库可以做到这一点吗?
答案 0 :(得分:2)
signal
是C函数。为了使C函数调用D函数,D函数应标记为extern(C) signalHandler()
。
import std.stdio;
extern(C) void signal(int sig, void function(int) );
// Our handler, callable by C
extern(C) void handle(int sig) {
writeln("Signal:",sig);
}
void main()
{
enum SIGINT = 2; // OS-specific
signal(SIGINT,&handle);
writeln("Hello!");
readln();
writeln("End!");
}
对于您的vibe.d示例,vibe.d自行处理SIGINT。这应该起作用:
import vibe.vibe;
void main()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, &hello);
logInfo("Please open http://127.0.0.1:8080/ in your browser.");
runApplication();
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody("Hello, World!");
}
运行此程序并按C-c。
09:21:59 ~/code/d/stackoverflow/q1
$ ./q1
[main(----) INF] Listening for requests on http://[::1]:8080/
[main(----) INF] Listening for requests on http://127.0.0.1:8080/
[main(----) INF] Please open http://127.0.0.1:8080/ in your browser.
^C[main(----) INF] Received signal 2. Shutting down.
Warning (thread: main): leaking eventcore driver because there are still active handles
FD 6 (streamListen)
FD 7 (streamListen)
Warning (thread: main): leaking eventcore driver because there are still active handles
FD 6 (streamListen)
FD 7 (streamListen)
09:22:04 ~/code/d/stackoverflow/q1
$