windows OnInitDialog
HANDLE m_hMutex = ::CreateMutex(NULL, TRUE, _T("SZSEL2Collecter"));
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
if (MessageBox(_T("SZSEL2Collecter采集程序已正在运行,是否再次运行?"), _T("警告"), MB_YESNO) == IDNO)
{
PostQuitMessage(0);
CloseHandle(m_hMutex);
return TRUE;
}
}
// Linux 下面用文件锁实现进程只能打开单个实例,win32 用createMutex实现。
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define TestLockfile "OneInstance.pid"
int ValidProcessRun(char* lockfile)
{
int fd;
fd = open(lockfile, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(fd < 0){
printf("can't open the lock file: %s \n",lockfile);
return -1;
}
// 进行加锁操作
struct flock f1;
f1.l_type = F_WRLCK; // 设置为唯一写锁,如果是同一个进程不会失败,会替换原来的锁。
f1.l_start = 0;
f1.l_whence = SEEK_SET;
f1.l_len = 0; // 设置锁的大小为为整个文件
if(fcntl(fd, F_SETLK, &f1) < 0){
if(errno == EACCES || errno == EAGAIN){
printf("The process has only one instance.\n");
close(fd);
return -1;
}
printf("can't lock.\n");
return -1;
}
// 截断文件
ftruncate(fd, 0);
char buf[32];
sprintf(buf, "%ld", (long)getpid());
write(fd, buf, strlen(buf)+1);
return 0;
}
int main(){
if(ValidProcessRun(TestLockfile) == -1) //进程如果启动就报进程只能启动一次
exit(1);
while(1){
printf("Runing...\n");
sleep(1);
}
return 0;
}