001 (ns dog-and-duck.utils.process
002 (:require [clojure.string :refer [split]]))
003
004 ;;; Copyright (C) Simon Brooke, 2022
005
006 ;;; This program is free software; you can redistribute it and/or
007 ;;; modify it under the terms of the GNU General Public License
008 ;;; as published by the Free Software Foundation; either version 2
009 ;;; of the License, or (at your option) any later version.
010
011 ;;; This program is distributed in the hope that it will be useful,
012 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
013 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 ;;; GNU General Public License for more details.
015
016 ;;; You should have received a copy of the GNU General Public License
017 ;;; along with this program; if not, write to the Free Software
018 ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
019
020 (def get-pid
021 "Get the process id of the current process.
022
023 OK, this is hacky as fuck, but I hope it works. The problem is that the
024 way to get the process id has changed several times during the history
025 of Java development, and the code for one version of Java won't even compile
026 in a different version."
027 (memoize
028 (fn []
029 (let [java-version (read-string (apply str (take 2
030 (split
031 (System/getProperty "java.version")
032 #"[_\.]"))))
033 cmd (case java-version
034 18 "(let [[_ pid hostname]
035 (re-find
036 #\"^(\\d+)@(.*)\"
037 (.getName
038 (java.lang.management.ManagementFactory/getRuntimeMXBean)))]
039 pid)"
040 (19 110) "(.pid (java.lang.ProcessHandle/current))"
041 111 "(.getPid (java.lang.management.ManagementFactory/getRuntimeMXBean))"
042 ":default")]
043 (eval (read-string cmd))))))
044
045 (def get-hostname
046 "return the hostname of the current host.
047
048 Java's methods for getting the hostname are quite startlingly slow, we
049 do not want todo this repeatedly!"
050 (memoize (fn [] (.. java.net.InetAddress getLocalHost getHostName))))