日期:2014-05-16  浏览次数:20560 次

如何查找指定进程的PID,通过编程解决?
已知所要查找的进程肯定在运行之中。
如何通过编程得知该进程的pid号。

最好有C或C++代码作为例子,谢谢!!

系统是linux   FC5。

------解决方案--------------------
遍历/proc目录下的每一个数字命名的子目录,每一个子目录是一个进程的相关信息,其中文件cmdline包含进程所运行的程序文件名

例如/proc/1/cmdline包含的是
init

------解决方案--------------------
1. 用waitpid可以获得子进程的pid

2. 用getpid可以获得当前进程的pid

3. 用system()执行shell命令 ps -ax | grep "程序名 "|awk '{print $1} '

------解决方案--------------------
看我这段代码能否达到楼主的要求:
-----------------------
int find_pid_by_name(vector <long> &vec_proid, char* pidName)
{
DIR *dir;
struct dirent *next;
int i=0;

dir = opendir( "/proc ");
if (!dir)
{
fprintf(stderr, "Cannot open /proc\n ");
return -999;
}

while ((next = readdir(dir)) != NULL)
{
FILE *status;
char filename[READ_BUF_SIZE];
char buffer[READ_BUF_SIZE];
char name[READ_BUF_SIZE];

/* Must skip ".. " since that is outside /proc */
if (strcmp(next-> d_name, ".. ") == 0)
continue;

/* If it isn 't a number, we don 't want it */
if (!isdigit(*next-> d_name))
continue;

sprintf(filename, "/proc/%s/status ", next-> d_name);
if (! (status = fopen(filename, "r ")) )
{
continue;
}
/* Read first line in /proc/?pid?/status */
if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
{
fclose(status);
continue;
}
fclose(status);

/* Buffer should contain a string like "Name: binary_name " */
sscanf(buffer, "%*s %s ", name);
if (strcmp(name, pidName) == 0)
{
printf( "PID:[%d][%s]\n ", strtol(next-> d_name, NULL, 0), next-> d_name);
vec_proid.push_back(strtol(next-> d_name, NULL, 0));
}
}
return 0;
}

-----------------------
------解决方案--------------------
#include <stdlib.h>

system( "脚本绝对路径名 ")

或者用exec()也行。