程序名称可以被改
#include <QApplication>
#include <QLocalSocket>
#include <QLocalServer>
#include <QFile>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
size_t get_executable_path( char* processdir,char* processname, size_t len)
{
char* path_end;
if(readlink("/proc/self/exe", processdir,len) <=0)
return -1;
path_end = strrchr(processdir, '/');
if(path_end == NULL)
return -1;
++path_end;
strcpy(processname, path_end );
*path_end = '\0';
return (size_t)(path_end - processdir);
}
bool is_running;
QLocalServer *server;
void checkSinglt()
{
char path[200];
char processname[50];
memset( path, 0, 200 );
memset( processname, 0, 50 );
std::cout<<"@@@ @@###### Check Instance!!! #######@@ @@@"<<std::endl;
is_running = false;
size_t sizx = get_executable_path( path, processname, sizeof(path) );
QCoreApplication::setApplicationName(processname);
QString serverName = QCoreApplication::applicationName();
QLocalSocket socket;
socket.connectToServer(serverName);
if(socket.waitForConnected(500))
{
is_running =true;
return;
}
//连接不上服务器,就创建一个
server =new QLocalServer();
// connect(server, SIGNAL(newConnection()), this,SLOT(newLocalConnection()));
if(server->listen(serverName))
{
//防止程序崩溃时,残留进程服务,移除之
if( server->serverError() == QAbstractSocket::AddressInUseError &&QFile::exists(server->serverName()))
{
QFile::remove(server->serverName());
server->listen(serverName);
}
}
}
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
checkSinglt();
if(is_running)
{
std::cout<<"@@@ Error Exist Instance"<<std::endl;
QMessageBox::information(NULL, "Singnlt", "Error Already Has An Instance!!!", QMessageBox::Ok);
exit(0);
}
return a.exec();
}