0

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?

5
  • 1
    lsof
    – bansi
    Feb 22, 2017 at 3:00
  • 2
    by parse "/proc", I can get all opening file. I want to know whether there is a better way
    – tacy_lee
    Feb 22, 2017 at 3:01
  • just check my first comment and here is some examples and btw, you can use logrotate to compress and archive the logs automatically, then delete it later (may be with a script)
    – bansi
    Feb 22, 2017 at 3:01
  • Thanks bansi, I want to implement a agent that it will running on docker container environment, it cant't have too much process, also crontab
    – tacy_lee
    Feb 22, 2017 at 3:12
  • another option is you can safely remove lines from the top of the log file even if it is open, if your environment has sed or tail
    – bansi
    Feb 22, 2017 at 3:24

3 Answers 3

1

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.

0

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.

-1

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.