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;
}

最新文章

  1. Maven_profile_使用profile配置不同环境的properties(实践)
  2. 如何在cmd下切换不同版本的Python
  3. ASP.NET发布后,功能不响应
  4. for循环求交集
  5. 深入理解js——执行上下文
  6. AndroidStudio开发工具快捷键
  7. Ubuntu12.04下载Android4.0.1源码全过程,附若干问题解决[转]
  8. A Game of Thrones(2) - Catelyn
  9. SVA(system verilog assertions)基础
  10. Action写法心得
  11. verilog实现红黄蓝三秒灯
  12. Unity --- sharedMaterial 、material
  13. BCS SET EMAIL
  14. JAVA企业级快速开发平台,JEECG 3.7.3 新春版本发布
  15. 卷积神经网络(CNN)之一维卷积、二维卷积、三维卷积详解
  16. 转 configure: error: Cannot find ldap libraries in /usr/lib 解决办法
  17. 001-nginx基础配置-location
  18. Linux系统内存管理
  19. Android系统示例分析之AccelerometerPlay
  20. 怎么使用Vue-cli3开发像iview、element那样的组件可下载直接使用

热门文章

  1. hdu4565
  2. Java数据结构和算法(七)--AVL树
  3. spring深入学习(六)-----springmvc
  4. Linux/UNIX之信号(1)
  5. day37 04-Hibernate二级缓存:list和iterate方法比较
  6. python实例 函数
  7. 【洛谷P1632】点的移动
  8. js实现放大镜特效的实现方法
  9. PHP通过sql生成CSV文件并下载,PHP实现文件下载
  10. Watering Grass (贪心,最小覆盖)