forked from gcla/termshark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fdinfo.go
67 lines (58 loc) · 1.67 KB
/
fdinfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2019 Graham Clark. All rights reserved. Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.
package termshark
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"github.com/gcla/gowid"
)
//======================================================================
var re *regexp.Regexp = regexp.MustCompile(`^pos:\s*([0-9]+)`)
var FileNotOpenError = fmt.Errorf("Could not find file among descriptors")
var ParseError = fmt.Errorf("Could not match file position")
// current, max
func ProcessProgress(pid int, filename string) (int64, int64, error) {
filename, err := filepath.EvalSymlinks(filename)
if err != nil {
return -1, -1, err
}
fi, err := os.Stat(filename)
if err != nil {
return -1, -1, err
}
finfo, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", pid))
if err != nil {
return -1, -1, err
}
fd := -1
for _, f := range finfo {
lname, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/%s", pid, f.Name()))
if err == nil && lname == filename {
fd, _ = strconv.Atoi(f.Name())
break
}
}
if fd == -1 {
return -1, -1, gowid.WithKVs(FileNotOpenError, map[string]interface{}{"filename": filename})
}
info, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/fdinfo/%d", pid, fd))
matches := re.FindStringSubmatch(string(info))
if len(matches) <= 1 {
return -1, -1, gowid.WithKVs(ParseError, map[string]interface{}{"fdinfo": finfo})
}
pos, err := strconv.ParseUint(matches[1], 10, 64)
if err != nil {
return -1, -1, err
}
return int64(pos), fi.Size(), nil
}
//======================================================================
// Local Variables:
// mode: Go
// fill-column: 78
// End: