简体   繁体   English

仅当进程仍拥有unix套接字时,才取消链接/清理

[英]Unlink/cleanup unix socket only if it's still owned by process

First time working with Unix domain sockets, now I'm trying to implement the cleanup part. 第一次使用Unix域套接字,现在我正在尝试实现清理部分。

It already seemed a bit ugly that the general recommendation when creating your listening socket is to first try to unlink the desired socket path and then call bind. 创建监听套接字的一般建议是先尝试取消链接所需的套接字路径,然后调用bind,这似乎有些丑陋。 While you probably should make sure that your process is only running once, I'm trying to prepare for the situation where for some reason it will be launched twice. 尽管您可能应该确保您的进程仅运行一次,但我正在尝试为因某种原因将两次启动的情况做准备。 For the service itself it doesn't matter too much: The first instance's socket is unlinked by the second instance, so it's unreachable, wastes some RAM, but doesn't do any harm. 对于服务本身而言,并没有太大关系:第一个实例的套接字未与第二个实例链接,因此它是不可访问的,浪费了一些RAM,但没有任何危害。 But how would I implement cleanup that works in this situation? 但是,在这种情况下,我将如何实施清理呢? Simply doing 简单地做

close(sockFd);
unlink(sockPath);

would lead to the situation that if the first process exits while the second is still running, it would actually delete the second process' socket from the file system. 会导致以下情况:如果第一个进程退出而第二个进程仍在运行,则实际上会从文件系统中删除第二个进程的套接字。 Boom, no service. 景气,没有服务。

I can only think of a few ugly hacks that wouldn't be atomic so could still mess things up, so I'm hoping there is a better paradigm to prevent ending up in this situation. 我只能想到一些不是原子的丑陋的骇客,因此仍然可能使事情变得混乱,所以我希望有一个更好的范例来防止在这种情况下结束。 Something like funlink(sockFd) would have been nice. 像funlink(sockFd)之类的东西会很好。 Otherwise I'd have to resort to never cleaning up the socket, which isn't the end of the world, but feels quite messy to me. 否则,我不得不求助于永远不要清理套接字,这不是世界末日,但对我来说却很混乱。

Abstract domain sockets looked quite promising (even though it would tie me to Linux for now), but unfortunatly they don't seem to support permissions, which is a requirement in my case. 抽象域套接字看起来非常有前途(即使现在可以将我绑定到Linux),但是不幸的是它们似乎不支持权限,这在我的情况下是必需的。

You could use a separate lock file that your application locks with flock(..., LOCK_EX) before doing anything with the socket. 在对套接字执行任何操作之前flock(..., LOCK_EX)可以使用应用程序使用flock(..., LOCK_EX)锁定的单独锁定文件。 As long as all application instances agree on what lock file to use you are safe, and flock() is atomic. 只要所有应用程序实例都同意使用哪个锁文件是安全的,并且flock()是原子的。 Cleanup is no issue with flock() as the lock is released when the process dies. flock()清理不是问题,因为进程死后将释放锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM