红联Linux门户
Linux帮助

Linux环境下C++只允许单个程序运行

发布时间:2016-09-07 15:25:13来源:linux网站作者:m沉默01
本程序在Ubuntu和Centos系统下能够正常使用!
 
具体实现的代码:
bool isSingleProcess ()  
{  
long pid;  
char full_name[1024] = {0};  
char proc_name[1024] = {0};  
int fd;  
pid = getpid();  
cout << "pid = " << pid;  
sprintf(full_name, "/proc/%ld/cmdline", pid);  
if (access(full_name, F_OK) == 0)  
{  
fd = open (full_name, O_RDONLY);  
if (fd == -1)  
return false;  
read (fd, proc_name, 1024);  
close (fd);  
}  
else  
return false; 
char self_proc_name[512] = {0};  
char * p = proc_name;  
int pt = 0;  
while (*p != ' ' && *p != '\0')  
{  
self_proc_name[pt] = *p;  
p++;  
pt++;  
}  
string self_final_name = basename(self_proc_name);  
cout << "self_final_name = " << self_final_name << endl << flush;  
DIR *dir;  
struct dirent * result;  
dir = opendir ("/proc");  
while ((result = readdir (dir)) != NULL)  
{  
if (! strcmp(result->d_name, ".") || ! strcmp (result->d_name, "..") || ! strcmp (result->d_name, "thread-self")  
|| ! strcmp (result->d_name, "self") || atol (result->d_name) == pid)  
continue;  
memset(full_name, 0, sizeof(full_name));  
memset(proc_name, 0, sizeof(proc_name));  
sprintf(full_name, "/proc/%s/cmdline", result->d_name);  
if (access(full_name, F_OK) == 0)  
{  
fd = open (full_name, O_RDONLY);  
if (fd == -1)  
continue;  
read (fd, proc_name, 1024);  
close (fd);  
char *q = proc_name;  
pt = 0;  
memset(self_proc_name, 0, sizeof (self_proc_name));  
while (*q != ' ' && *q != '\0')  
{  
self_proc_name[pt] = *q;  
q++;  
pt++;  
}  
string other_final_name = basename(self_proc_name);  
if (self_final_name == other_final_name)  
{  
cout << "full_name = " << full_name << endl << flush;  
cout << "other_final_name: " << other_final_name << endl;  
return true;  
}  
}  
}  
return false;  
}  
 
在main函数中的开始添加以下内容:
int main (int argc, char ** argv)  
{
// judge single  
if (isSingleProcess())  
{  
cout << "process is running in another place" << endl << flush;  
return 0;  
......  
return 0;  
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/23961.html