从/ proc获取值

时间:2013-12-09 19:37:15

标签: java

我想获取正在运行的进程列表和/ proc文件系统中的值:

这是我想要搜索数据的结构,例如:

/proc/24/status
/proc/344/status
/proc/456/status
.......

我做了这么快的代码:

public void initSystemProcesses() throws FileNotFoundException, IOException
    {

        BufferedReader dataReader = null;
        String freeLine;
        String[] freeChunkedLine;
        HashMap<String, String> usageData = new HashMap<>();

        File f = new File("/proc");

        for (File names : f.listFiles())
        {
            if (names.isDirectory())
            {
                File[] subDir = names.listFiles();

                for (File subDirs : subDir)
                {

                    dataReader = new BufferedReader(new InputStreamReader(new FileInputStream("subDirs/status")));
                    freeLine = dataReader.readLine();

                    String daemonName = null;
                    String nameValue = null;
                    while (freeLine != null)
                    {
                        freeChunkedLine = freeLine.split("\\s+");
                        String name = freeChunkedLine[0];
                        String value = freeChunkedLine[1];

                        if (name.indexOf("Name:") != -1 || name.indexOf("State:") != -1)
                        {
                            String vv = null;
                            usageData.put(name, vv);
                            if (name.equals("Name:"))
                            {
                                daemonName = vv;
                            }
                            if (name.equals("State:"))
                            {
                                nameValue = vv;
                            }

                            //TODO insert the data into array

                        }

                        freeLine = dataReader.readLine();
                    }

                }

            }
        }

    }

代码未经过测试,我可能会有错误。

这是状态文件的内容:

Name:    kthreadd
State:    S (sleeping)
Tgid:    2
Pid:    2
PPid:    0

你能帮我制作一个有效的代码来循环文件夹并从状态文件中获取值吗?

1 个答案:

答案 0 :(得分:0)

我不知道你真正的问题,但我想,这条线可能是错误的:

dataReader = new BufferedReader(new InputStreamReader(new FileInputStream("subDirs/status")));

这应该是这样的:

dataReader = new BufferedReader(new InputStreamReader(new FileInputStream(subDirs.getAbsolutePath() + "/status")));

目录应为数字(对于进程),因此添加如下条件:

if (subDirs.getName().matches("^[0-9]+$")) ...