我想通过停止事件循环来优雅地关闭vibe.d应用程序。
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();
}
不幸的是,这不起作用:
source/app.d(7,9): Error: function core.stdc.signal.signal(int sig, extern (C) void function(int) nothrow @nogc @system func) is not callable using argument types (int, void function(int value))
source/app.d(7,9): cannot pass argument & stopapp of type void function(int value) to parameter extern (C) void function(int) nothrow @nogc @system func
dmd failed with exit code 1.
有一个简单的库可以做到这一点吗?
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!");
}
对于您的 vivi.d 示例,vib.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
$
而不是
listenHTTP(settings, &hello);
使用
auto listener = listenHTTP(settings, &hello);
scope(exit) {listener.stopListening;}