在linux下通过进程名获取进程id,一般使用ps命令,ps -A |grep openvpn。
其实linux的每个进程都会在/proc伪目录下存放相应信息。
先给出c程序
添加头文件
#include
#include
#define READ_BUF_SIZE 50
函数
pid_t* find_pid_by_name( char* pidName)
{
DIR *dir;
struct dirent *next;
pid_t* pidList=NULL;
int i=0;
dir = opendir("/proc");
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;
}
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) {
pidList=realloc( pidList, sizeof(pid_t) * (i+2));
pidList[i++]=strtol(next->d_name, NULL, 0);
}
}
return pidList;
}
调用方法
pid_t* pidList, *tmpList;
pidList = find_pid_by_name("openvpn");
if (!pidList || *pidList<=0) {
}
tmpList = pidList;
for(; pidList && *pidList!=0; pidList++)
{
}
free(tmpList);
java的原理类似,我引入apache的commons io,其实这个包可以不用
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
先写一个filter
public class PidFileFilter implements FileFilter
{
public boolean accept(File file)
{
String fileName = file.getName();
char digit = fileName.charAt(0);
if(Character.isDigit(digit))
{
return true;
}
return false;
}
}
不是数字开头的全不要
函数 返回一个list,里面存有所有的pid
public List getPid(String processname)
{
File rootFolder = new File("/proc");
File[] files = rootFolder.listFiles(new PidFileFilter());
List ls=new ArrayList();
for (File f : files)
{
File file1 = new File("/proc/"+f.getName()+"/status");
try {
LineIterator it = FileUtils.lineIterator(file1, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
String []name = line.split("\t") ;
if(name[0].equals("Name:") && name[1].equals(processname))
{
ls.add(f.getName());
}
break;
}
} finally {
LineIterator.closeQuietly(it);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return ls;
}
相比之下 ,觉得还是c语言逻辑清晰,代码容易理解。
阅读(1437) | 评论(0) | 转发(0) |