I want to delete some logs when logs size exceed quota, But I need to check if the log is opening before delete it.
How to get all open files by current user?
Parsing /proc (see proc(5)...) is probably the most efficient way and is what lsof
would do.
You could first scan all (numeric) directories to find processes running by your users, than in all such directories use the /proc/
pid/fd
directory.
BTW, you might not care and just remove these log files. The kernel will behave appropriately if it was opened.
But perhaps you should ask your sysadmin to setup disk quotas. See quota(1) & quotaon(8).
Perhaps using & configuring logrotate should be enough.
If you're bash scripting, lsof
might fit your need. If you're interested in the user with username X, lsof -uX
should do the trick.
by parse "/proc" get all open file:
func getOpenfiles() (openfiles map[string]bool) {
files, _ := ioutil.ReadDir("/proc")
openfiles = make(map[string]bool)
for _, f := range files {
m, _ := filepath.Match("[0-9]*", f.Name())
if f.IsDir() && m {
fdpath := filepath.Join("/proc", f.Name(), "fd")
ffiles, _ := ioutil.ReadDir(fdpath)
for _, f := range ffiles {
fpath, err := os.Readlink(filepath.Join(fdpath, f.Name()))
if err != nil {
continue
}
openfiles[fpath] = true
}
}
}
return openfiles
}
sed
ortail