如何在 C 或 C++ 中创建单实例应用程序 [英] How to create a single instance application in C or C++

查看:27
本文介绍了如何在 C 或 C++ 中创建单实例应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了创建单实例应用程序,以便一次只允许运行一个进程,您有什么建议?文件锁,互斥锁还是什么?

What would be your suggestion in order to create a single instance application, so that only one process is allowed to run at a time? File lock, mutex or what?

推荐答案

一个好方法是:

#include <sys/file.h>
#include <errno.h>

int pid_file = open("/var/run/whatever.pid", O_CREAT | O_RDWR, 0666);
int rc = flock(pid_file, LOCK_EX | LOCK_NB);
if(rc) {
    if(EWOULDBLOCK == errno)
        ; // another instance is running
}
else {
    // this is the first instance
}

请注意,锁定允许您忽略陈旧的 pid 文件(即您不必删除它们).当应用程序因任何原因终止时,操作系统会为您释放文件锁.

Note that locking allows you to ignore stale pid files (i.e. you don't have to delete them). When the application terminates for any reason the OS releases the file lock for you.

Pid 文件不是很有用,因为它们可能是陈旧的(文件存在但进程不存在).因此,可以锁定应用程序可执行文件本身,而不是创建和锁定 pid 文件.

Pid files are not terribly useful because they can be stale (the file exists but the process does not). Hence, the application executable itself can be locked instead of creating and locking a pid file.

更高级的方法是使用预定义的套接字名称创建和绑定 unix 域套接字.应用程序的第一个实例绑定成功.同样,当应用程序因任何原因终止时,操作系统会解除套接字的绑定.当 bind() 失败时,应用程序的另一个实例可以 connect() 并使用此套接字将其命令行参数传递给第一个实例.

A more advanced method is to create and bind a unix domain socket using a predefined socket name. Bind succeeds for the first instance of your application. Again, the OS unbinds the socket when the application terminates for any reason. When bind() fails another instance of the application can connect() and use this socket to pass its command line arguments to the first instance.

这篇关于如何在 C 或 C++ 中创建单实例应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆