- 论坛徽章:
- 0
|
如何保证一个程序同时只有一个实例(进程)运行?
没必要用文件锁那么复杂,用popen 即可,这儿有个现成的函数,可以判断同名进程已经起了几个。
/************************************
* 函 数 名: int CheckPoc(char * ppszProcess)
* 文 件 名: CheckProc.c
* 入口参数: ppszProcess:进程名
*
* 返回参数: 进程数
* 函数功能: 检查进程数,并可用于杀进程使用
***************************************/
int CheckProc(ppszProcess)
char * ppszProcess;
{
FILE *fp;
char buffer[300], cmd[20];
char pid[20], temp[20],proc[20];
int i = 0;
sprintf(temp,"ps -ef|grep %s",ppszProcess);
if((fp = popen(temp, "r" ) != NULL)
{
while (fgets(buffer, 128, fp))
{
sscanf(buffer, "%*s%s%*s%*s%*s%*s%*s%s", pid,proc);
if (strstr(proc, ppszProcess)!=NULL && atoi(pid)!=getpid())
i++;
}
}
pclose(fp);
return (i);
} |
|