2013-08-28 35 views
4

我需要訪問Android內核模塊中的一些proc文件。 基本上我需要在cat命令中顯示的信息,如cat /proc/uptime。不過,我需要通過編程來完成。從內核模塊中的proc文件訪問數據

我嘗試過使用proc_fs函數,但對我來說只是有點模糊,通常這些例子是創建一個proc文件然後讀取它,就是這樣。我需要實際使用proc文件中的數據。

我也提供了很好的fopen,但它似乎並不適用於模塊。

我該怎麼做?我真的很新鮮。 我正在研究金魚Android內核。

謝謝。

+0

您是否嘗試讀取/ proc/foo,就像您將正常文件一樣?全部閱讀,然後解析它。順便說一下,'linux-kernel'會是這個問題的更好標記。 –

+0

我試過了,不起作用。謝謝你的提示。 – douglasd3

+0

爲什麼有人想在內核上下文中使用proc fs,他們爲了用戶空間,爲什麼不直接使用數據結構和全局proc從何處獲取信息。 –

回答

4

Procfs是一個內存中的文件系統。它是用戶空間獲取信息並將(配置)信息放入內核數據結構的接口。換句話說,procfs使用戶空間能夠以運行時存在的方式交互並查看內核數據結構。

因此,/ proc中的任何文件都是而不是,意味着要從內核或內核模塊中讀取。爲什麼要這樣做呢?在像Linux這樣的單一內核中,您可以直接或通過預定義的函數通過另一個子系統訪問內核中的一個子系統的數據結構。

下面的函數調用可能會有所幫助:

struct timespec uptime; 

do_posix_clock_monotonic_gettime(&uptime); 

你可以參考在/ proc /運行時間實現在下面的鏈接,它本質上是一個seq_file

http://lxr.free-electrons.com/source/fs/proc/uptime.c

+0

我的目標實際上是估計給定進程的CPU使用情況。我按照這個接受的答案進入proc文件http://stackoverflow.com/a/16736599/1132848 但我想我有主要想法。謝謝 – douglasd3

0

我用頂部做到這一點,因爲它實際上給CPU%。我使用的代碼如下

Process process = Runtime.getRuntime().exec("top -n 1"); 
       //Get the output of top so that it can be read 
       BufferedReader bufferedReader = new BufferedReader(
       new InputStreamReader(process.getInputStream())); 
       String line; 
       //Read every line of the output of top that contains data 
       while (((line = bufferedReader.readLine()) != null)) { 
        //Break the line into parts. Any number of spaces greater than 0 defines a new element 
        numbersC = line.split("[ ]+");    
        if (i > 6) { 
         //Some lines start with a space, so their indices are different than others 
         if (numbersC[0].equals("")){ 
          //If name contains the string com.android, then it is a process that we want to take values for 
          if (numbersC[numbersC.length - 1].toLowerCase().contains("com.android".toLowerCase())){ 
           //Add the name of the process to the Name arraylist, excluding the com.android. part 
           Name.add(numbersC[numbersC.length - 1].replace("com.android.", "")); 
           //Add the CPU value of the process to the CPU arraylist, without the % at the end 
           CPU.add(Long.parseLong(numbersC[3].replace("%", ""))); 
          } 
         } 
         else { 
          //This is basically the same as above, except with different index values, as there is no leading space in the numbers array 
          if (numbersC[numbersC.length - 1].toLowerCase().contains("com.android.".toLowerCase())){ 
           Name.add(numbersC[numbersC.length - 1].replace("com.android.", "")); 
           CPU.add(Long.parseLong(numbersC[2].replace("%", ""))); 
          } 
         } 
        } 
        i++; 
       } 
+0

這不是對問題的回答(尋求在內核*中獲取此信息),原因有三。首先,您正在使用'top',它直接與閱讀/ proc條目相比基本上是間接的。其次,你用java編寫,它不能在內核上下文中運行。第三,基本的問題是,/ proc(正如接受的答案中所解釋的)和'top'都不能用於內核上下文中。 –