之前写过一篇文章,linux下根据进程名字获取进程号,但是只能在linux下使用,这次更新一版,适合linux,AIX和hp-unix平台。
其实原理很简单,就是利用了ps命令,前段时间更新blog比较慢,工作忙....其实工作忙都是借口......
/***************************************************************************
* File name : findpidbyname.c
* Function : like pidof
* Author : [email protected]
* Date : 2013/08/
* Version : v1.0
* Description : Find process's pid by name in linux\aix\hp-ux
* ModifyRecord :
****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#define MAXBUFLEN 1024
#define HP_ENV "UNIX_STD"
int find_pid_by_name( char* ProcName, int* foundpid)
{
char c_result[MAXBUFLEN], c_command[MAXBUFLEN];
int i;
FILE *fp;
/*
* 在hp-unix环境下,需要在编译时加上-DHP
*
*/
#ifdef HP
int rv;
rv = setenv(HP_ENV, "2003", 1);
if(rv != 0)
{
printf("In HP-Unix environment, set env UNIX_STD failed! Can't find pid of %s", ProcName);
return -1;
}
#endif
snprintf(c_command, sizeof(c_command), "ps -eo pid,comm | grep -w %s | awk '{print $1}'", ProcName);
fp = popen(c_command, "r");
if(fp == NULL)
{
#ifdef HP
unsetenv(HP_ENV);
#endif
printf("popen failed, errno is %d.\n", errno);
return -1;
}
i = 0;
while(fgets(c_result, sizeof(c_result), fp) != NULL)
{
foundpid[i++] = atoi(c_result);
}
foundpid[i] = 0;
pclose(fp);
#ifdef HP
unsetenv(HP_ENV);
#endif
return 0;
}