获取进程PID

程序中经常需要有这么一个功能:只允许本程序的单个实例运行,即不能多次运行一个程序。检测某个进程是否在运行,在shell中可以很轻松的用命令ps -A|grep xxx找出来,但对于程序来说,该怎么检测呢?我参考了aecium 程序的方法:同样调用ps -A|grep xxx。也许会存在更先进的方法,比如dbus、系统信号量之类的技术,总之这个不会是最好的方法,不过且看看其技巧。

首先要获得当前进程的名字以便传给grep,一般通过main的argv[0]可得到运行时的程序名,不过要注意的是,通过路径运行的程序如./a.out,argv[0]也是./a.out的。

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <signal.h>
 
void program_unique_check( const char * program)
{
FILE * fd;
pid_t id = 0 ;
char command[ 50 ] = { 0 } ;
char pid_num[ 50 ] = { 0 } ;
const char * program_name;
 
program_name = strrchr ( program, '/' ) ;
 
//过滤得到程序的文件名
if ( program_name)
++ program_name;
else
program_name = program;
 
//组成执行的命令ps -Ao pid,comm|grep xxx
sprintf( command, "ps -Ao pid,comm|grep %s" , program_name) ;
 
printf ( "Command to excute: %s/n " , command) ;
 
//以管道方式执行命令
if ( ( fd = popen( command, "r" ) ) == NULL ) {
perror( "popen" ) ;
exit( EXIT_FAILURE) ;
}
 
//从管道读回执行结果,这里只为了取得PID,所以只读取前最多20个字符(PID不可能有那么长吧!)
fgets( pid_num, 20 , fd) ;
printf ( "Result :/n %s/n " , pid_num) ;
 
//转换结果字符为整形数值
id = atoi( pid_num) ;
printf ( "DETECTED PID: %d/n " , id) ;
 
//判断是否自己
if ( getpid( ) == id)
printf ( "This's my self: %d/n " , id) ;
else {
printf ( "Here's one already running: %d/n I'll kill him!/n " , id) ;
//SIGKILL信号,当然也可以是其他信号的
if ( kill ( id, SIGKILL) == - 1 ) {
perror( "kill" ) ;
exit( EXIT_FAILURE) ;
}
}
}
 
int main ( int argc, char ** argv)
{
program_unique_check( argv[ 0 ] ) ;
sleep ( 10 ) ;
return 0 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值