View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.util.platform.unix.freebsd;
6   
7   import java.util.HashMap;
8   import java.util.List;
9   import java.util.Map;
10  
11  import oshi.annotation.concurrent.ThreadSafe;
12  import oshi.util.ExecutingCommand;
13  import oshi.util.ParseUtil;
14  
15  /**
16   * Reads from procstat into a map
17   */
18  @ThreadSafe
19  public final class ProcstatUtil {
20  
21      private ProcstatUtil() {
22      }
23  
24      /**
25       * Gets a map containing current working directory info
26       *
27       * @param pid a process ID, optional
28       * @return a map of process IDs to their current working directory. If {@code pid} is a negative number, all
29       *         processes are returned; otherwise the map may contain only a single element for {@code pid}
30       */
31      public static Map<Integer, String> getCwdMap(int pid) {
32          List<String> procstat = ExecutingCommand.runNative("procstat -f " + (pid < 0 ? "-a" : pid));
33          Map<Integer, String> cwdMap = new HashMap<>();
34          for (String line : procstat) {
35              String[] split = ParseUtil.whitespaces.split(line.trim(), 10);
36              if (split.length == 10 && split[2].equals("cwd")) {
37                  cwdMap.put(ParseUtil.parseIntOrDefault(split[0], -1), split[9]);
38              }
39          }
40          return cwdMap;
41      }
42  
43      /**
44       * Gets current working directory info
45       *
46       * @param pid a process ID
47       * @return the current working directory for that process.
48       */
49      public static String getCwd(int pid) {
50          List<String> procstat = ExecutingCommand.runNative("procstat -f " + pid);
51          for (String line : procstat) {
52              String[] split = ParseUtil.whitespaces.split(line.trim(), 10);
53              if (split.length == 10 && split[2].equals("cwd")) {
54                  return split[9];
55              }
56          }
57          return "";
58      }
59  
60      /**
61       * Gets open files
62       *
63       * @param pid The process ID
64       * @return the number of open files.
65       */
66      public static long getOpenFiles(int pid) {
67          long fd = 0L;
68          List<String> procstat = ExecutingCommand.runNative("procstat -f " + pid);
69          for (String line : procstat) {
70              String[] split = ParseUtil.whitespaces.split(line.trim(), 10);
71              if (split.length == 10 && !"Vd-".contains(split[4])) {
72                  fd++;
73              }
74          }
75          return fd;
76      }
77  }