Scotty申请终止后清理

时间:2015-09-05 18:45:39

标签: haskell scotty

我有一个侦听Unix套接字的Scotty应用程序。我希望应用程序在退出时删除套接字(即当我键入 Ctrl - C )时,但我不知道如何完成此操作。我的main函数看起来像

main = do
    sock <- socket AF_UNIX Stream 0
    bind sock $ SockAddrUnix "/tmp/my_app.sock"
    listen sock maxListenQueue

    scottySocket def sock $ do
        ...

    removeFile "/tmp/my_app.sock"

当我输入 Ctrl - C 时,removeFile函数未被调用 - 这似乎是Scotty框架没有或无法捕获的中断。有没有办法执行这样的清理操作?

1 个答案:

答案 0 :(得分:2)

最简单的原则可能是使用Control.Exception中的bracket

main = bracket acquireSock cleanupSock $ \(sock, _) -> do
    listen sock maxListenQueue
    scottySocket def sock $ do
        ...
    where
    -- Acquiring the resource.
    acquireSock = do
        sock <- socket AF_UNIX Stream 0
        let sockPath = "/tmp/my_app.sock"
        bind sock $ SockAddrUnix sockPath
        return (sock, sockPath)
    -- Releasing the resource.
    cleanupSock (sock, sockPath) = do
        removeFile sockPath
        close sock