Linux保证运行一个实例
2024-10-08 00:58:54
1.
const int PATH_MAX = ; // 默认最大路径长度
inline std::string current_exe_name()
{
char buf[PATH_MAX] = {}; int ret = readlink("/proc/self/exe", buf, PATH_MAX);
if (ret < || ret >= PATH_MAX) {
return "";
} std::string path(buf);
std::size_t pos = path.find_last_of("/");
if (pos == std::string::npos) {
return "";
} path = path.substr(pos + , path.size() - ); return path;
} inline bool check_single_instance()
{
// 打开或创建一个文件
std::string file_path = "./pid.lck";
int fd = open(file_path.c_str(), O_RDWR | O_CREAT, );
if (fd < ) {
printf("Open file failed, error : %s", strerror(errno));
exit();
} // 将该文件锁定
// 锁定后的文件将不能够再次锁定
struct flock fl;
fl.l_type = F_WRLCK; // 写文件锁定
fl.l_start = ;
fl.l_whence = SEEK_SET;
fl.l_len = ;
int ret = fcntl(fd, F_SETLK, &fl);
if (ret < ) {
if (errno == EACCES || errno == EAGAIN) {
printf("%s already locked, error: %s\n", file_path.c_str(), strerror(errno));
close(fd);
return false;
}
} // 锁定文件后,将该进程的pid写入文件
char buf[] = {};
sprintf(buf, "%d", getpid());
ftruncate(fd, );
ret = write(fd, buf, strlen(buf));
if (ret < ) {
printf("Write file failed, file: %s, error: %s\n", file_path.c_str(), strerror(errno));
close(fd);
exit();
} // 函数返回时不需要调用close(fd)
// 不然文件锁将失效
// 程序退出后kernel会自动close
return true;
}
2
inline bool check_single_instance()
{
// 打开或创建一个文件
std::string file_path = "./pid.lck";
int fd = open(file_path.c_str(), O_RDWR | O_CREAT, );
if (fd < ) {
printf("Open file failed, error : %s", strerror(errno));
exit();
} // 将该文件锁定
// 锁定后的文件将不能够再次锁定
int ret = lockf(fd, F_TLOCK, );
if (ret < ) {
if (errno == EACCES || errno == EAGAIN) {
printf("%s already locked, error: %s\n", file_path.c_str(), strerror(errno));
close(fd);
return false;
}
} // 锁定文件后,将该进程的pid写入文件
char buf[] = {};
sprintf(buf, "%d", getpid());
ftruncate(fd, );
ret = write(fd, buf, strlen(buf));
if (ret < ) {
printf("Write file failed, file: %s, error: %s\n", file_path.c_str(), strerror(errno));
close(fd);
exit();
} // 函数返回时不需要调用close(fd)
// 不然文件锁将失效
// 程序退出后kernel会自动close
return true;
}
最新文章
- Maven_profile_使用profile配置不同环境的properties(实践)
- 如何在cmd下切换不同版本的Python
- ASP.NET发布后,功能不响应
- for循环求交集
- 深入理解js——执行上下文
- AndroidStudio开发工具快捷键
- Ubuntu12.04下载Android4.0.1源码全过程,附若干问题解决[转]
- A Game of Thrones(2) - Catelyn
- SVA(system verilog assertions)基础
- Action写法心得
- verilog实现红黄蓝三秒灯
- Unity --- sharedMaterial 、material
- BCS SET EMAIL
- JAVA企业级快速开发平台,JEECG 3.7.3 新春版本发布
- 卷积神经网络(CNN)之一维卷积、二维卷积、三维卷积详解
- 转 configure: error: Cannot find ldap libraries in /usr/lib 解决办法
- 001-nginx基础配置-location
- Linux系统内存管理
- Android系统示例分析之AccelerometerPlay
- 怎么使用Vue-cli3开发像iview、element那样的组件可下载直接使用