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

查看:125
本文介绍了如何创建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.

一个更先进的方法是创建并使用predefined套接字名称绑定Unix域套接字。绑定成功,您的应用程序的第一个实例。同样,OS解除绑定插座当应用程序因任何原因终止。当绑定()失败的应用程序的另一个实例可以连接(),并使用此接口将通过其命令行参数到第一个实例。

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天全站免登陆