Linux c 进程名 pid,linux 下根据进程名字获取进程的进程号PID,相似pidof,C函数

linux有一个命令行工具叫作pidof,能够根据用户输入的进程名字查找到进程号,但有时候咱们须要在程序里实现,不想调用system,在查阅了不少版本的pidof源代码后,没有发现一个本身感受比较好的,因此就参照linux上的pidof的源代码,改写出了一版,供你们参考使用。html

/***************************************************************************

* File name : findpidbyname.c

* Function : like pidof

* Author : zhangzhao@tass.com.cn

* Date : 2012/12/

* Version : v1.0

* Description : Find process's pid by name in linux.

* ModifyRecord :

****************************************************************************/

#include

#include

#include

#include

#include

int find_pid_by_name( char* ProcName, int* foundpid)

{

DIR *dir;

struct dirent *d;

int pid, i;

char *s;

int pnlen;

i = 0;

foundpid[0] = 0;

pnlen = strlen(ProcName);

/* Open the /proc directory. */

dir = opendir("/proc");

if (!dir)

{

printf("cannot open /proc");

return -1;

}

/* Walk through the directory. */

while ((d = readdir(dir)) != NULL) {

char exe [PATH_MAX+1];

char path[PATH_MAX+1];

int len;

int namelen;

/* See if this is a process */

if ((pid = atoi(d->d_name)) == 0) continue;

snprintf(exe, sizeof(exe), "/proc/%s/exe", d->d_name);

if ((len = readlink(exe, path, PATH_MAX)) < 0)

continue;

path[len] = '\0';

/* Find ProcName */

s = strrchr(path, '/');

if(s == NULL) continue;

s++;

/* we don't need small name len */

namelen = strlen(s);

if(namelen < pnlen) continue;

if(!strncmp(ProcName, s, pnlen)) {

/* to avoid subname like search proc tao but proc taolinke matched */

if(s[pnlen] == ' ' || s[pnlen] == '\0') {

foundpid[i] = pid;

i++;

}

}

}

foundpid[i] = 0;

closedir(dir);

return 0;

}

int main(int argc, char *argv[])

{

int i, rv, pid_t[128];

if ( argc != 2 )

{

fprintf(stdout,"Usage %s procname\n",argv[0]);

return 0;

}

rv = find_pid_by_name( argv[1], pid_t);

if(!rv) {

for(i=0; pid_t[i] != 0; i++)

printf("%d\n", pid_t[i]);

}

return 0;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值