FileObserver doesn't work for proc directory

1.2k views Asked by At

I use FileObserver to monitor '/proc/net/arp' directory,but I can't get any event in onEvent method.The code is below:

public class MyFileObserver extends FileObserver{

private Set<OnClientConnectListener> mListeners;
private boolean mWatching = false;

public MyFileObserver(String path) {
    super(path);
}

@Override
public void onEvent(int event, String path) {
    Log.d("conio","event:"+event+" , path:"+path);
    switch(event) {
    case FileObserver.MODIFY:
        Log.d("conio","event modify");
        ArrayList<String> ips = WifiHelper.getClientList(true, 3000);

        if(mListeners != null) {
            for(OnClientConnectListener lis : mListeners) {
                lis.onConnectChange(ips);
            }
        }
        break;
    }
}

How could I monitor '/proc/net/arp', I checked it has read perssion for this file , and I can use FileInputStream to read data from it.

1

There are 1 answers

1
Robin On BEST ANSWER

File observer is based on inotify mechanism, however, /proc is not generic file system. All the 'file' is just a interface to the kernel, through which you can get/set information from/to kernel. All the content is generated on the fly. That is why inotify is not work on /proc system. Please refer to this page.

However, users of Ubuntu 13.04 state that this works fine. Maybe the newest kernel supports such facility. I have copied the post here, the original page is here.

Compile the following program (inotifyerr.c)

#include <stdlib.h>
#include <stdio.h>
#include <sys/inotify.h>

int main(int argc, char* argv[]){
    int fd = inotify_init();
    if (fd == -1){
        perror("inotify_init");
    }
    char path[256];
    sprintf(path,"/proc/%s",argv[1]);
    printf("watching %s\n",path);
    int wd = inotify_add_watch(fd,path,IN_ALL_EVENTS);
    if (wd == -1){
        perror("inotify_add_watch");
    }
    char buf[1024];
    ssize_t siz = read(fd,buf,1024);
    if (siz == -1){
        perror("inotify read");
    }
    printf("read done, bytes: %d\n",siz);
}

gcc inotifyerr.c

Tested this on Ubuntu 13.04 and it is working fine:

sworddragon@ubuntu:~/data$ sleep 20 &
[1] 3009
sworddragon@ubuntu:~/data$ ls /proc/3009
attr cgroup comm cwd fd latency map_files mountinfo net oom_adj pagemap sched smaps statm task
autogroup clear_refs coredump_filter environ fdinfo limits maps mounts ns oom_score personality schedstat stack status wchan
auxv cmdline cpuset exe io loginuid mem mountstats numa_maps oom_score_adj root sessionid stat syscall
sworddragon@ubuntu:~/data$ ./a.out 3009
watching /proc/3009
read done, bytes: 128

Using inotifywait on /proc works fine too