View Javadoc
1   /*
2    * Copyright 2021-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.util.platform.unix.openbsd;
6   
7   import java.util.List;
8   
9   import oshi.annotation.concurrent.ThreadSafe;
10  import oshi.util.ExecutingCommand;
11  import oshi.util.ParseUtil;
12  
13  /**
14   * Reads from fstat.
15   */
16  @ThreadSafe
17  public final class FstatUtil {
18      private FstatUtil() {
19      }
20  
21      /**
22       * Gets current working directory info (using {@code ps} actually).
23       *
24       * @param pid a process ID
25       * @return the current working directory for that process.
26       */
27      public static String getCwd(int pid) {
28          List<String> ps = ExecutingCommand.runNative("ps -axwwo cwd -p " + pid);
29          if (ps.size() > 1) {
30              return ps.get(1);
31          }
32          return "";
33      }
34  
35      /**
36       * Gets open number of files.
37       *
38       * @param pid The process ID
39       * @return the number of open files.
40       */
41      public static long getOpenFiles(int pid) {
42          long fd = 0L;
43          List<String> fstat = ExecutingCommand.runNative("fstat -sp " + pid);
44          for (String line : fstat) {
45              String[] split = ParseUtil.whitespaces.split(line.trim(), 11);
46              if (split.length == 11 && !"pipe".contains(split[4]) && !"unix".contains(split[4])) {
47                  fd++;
48              }
49          }
50          // subtract 1 for header row
51          return fd - 1;
52      }
53  }