<p>How do I get the id of my Java process? </p>

<p>I know there are several platform-dependent hacks, but I would prefer a more generic solution.</p>

[{'answer_id': 35885, 'author': 'Wouter Coekaerts', 'author_id': 3432, 'author_profile': 'https://Stackoverflow.com/users/3432', 'pm_score': 10, 'selected': True, 'text': '<p>There exists no platform-independent way that can be guaranteed to work in all jvm implementations.\n<code>ManagementFactory.getRuntimeMXBean().getName()</code> looks like the best (closest) solution, and typically includes the PID. It\'s short, and <em>probably</em> works in every implementation in wide use.</p>\n<p>On linux+windows it returns a value like <code>&quot;12345@hostname&quot;</code> (<code>12345</code> being the process id). Beware though that <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getName%28%29" rel="noreferrer">according to the docs</a>, there are no guarantees about this value:</p>\n<blockquote>\n<p>Returns the name representing the running Java virtual machine. The\nreturned name string can be any arbitrary string and a Java virtual\nmachine implementation can choose to embed platform-specific useful\ninformation in the returned name string. Each running virtual machine\ncould have a different name.</p>\n</blockquote>\n<p><strong>In Java 9</strong> the new <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html" rel="noreferrer">process API</a> can be used:</p>\n<pre><code>long pid = ProcessHandle.current().pid();\n</code></pre>\n'}, {'answer_id': 42970, 'author': 'Ryan P', 'author_id': 1539, 'author_profile': 'https://Stackoverflow.com/users/1539', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on where you are looking for the information from.</p>\n\n<p>If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5</p>\n\n<p>If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]@[MACHINE_NAME]. You could however try to execute jps and parse the result from that:</p>\n\n<pre><code>String jps = [JDK HOME] + "\\\\bin\\\\jps.exe";\nProcess p = Runtime.getRuntime().exec(jps);\n</code></pre>\n\n<p>If run with no options the output should be the process id followed by the name.</p>\n'}, {'answer_id': 1962335, 'author': 'Jez Humble', 'author_id': 238714, 'author_profile': 'https://Stackoverflow.com/users/238714', 'pm_score': 4, 'selected': False, 'text': '<p>You can check out my project: <a href="http://github.com/jezhumble/javasysmon/" rel="noreferrer">JavaSysMon</a> on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris) </p>\n'}, {'answer_id': 3134967, 'author': 'Ashwin Jayaprakash', 'author_id': 257122, 'author_profile': 'https://Stackoverflow.com/users/257122', 'pm_score': 5, 'selected': False, 'text': '<p>Try <a href="http://support.hyperic.com/display/SIGAR/Home" rel="nofollow noreferrer">Sigar</a> . very extensive APIs.  Apache 2 license.</p>\n\n<pre class="lang-java prettyprint-override"><code>private Sigar sigar;\n\npublic synchronized Sigar getSigar() {\n    if (sigar == null) {\n        sigar = new Sigar();\n    }\n    return sigar;\n}\n\npublic synchronized void forceRelease() {\n    if (sigar != null) {\n        sigar.close();\n        sigar = null;\n    }\n}\n\npublic long getPid() {\n    return getSigar().getPid();\n}\n</code></pre>\n'}, {'answer_id': 6372205, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>For older JVM, in linux...</p>\n\n<pre><code>private static String getPid() throws IOException {\n    byte[] bo = new byte[256];\n    InputStream is = new FileInputStream("/proc/self/stat");\n    is.read(bo);\n    for (int i = 0; i &lt; bo.length; i++) {\n        if ((bo[i] &lt; \'0\') || (bo[i] &gt; \'9\')) {\n            return new String(bo, 0, i);\n        }\n    }\n    return "-1";\n}\n</code></pre>\n'}, {'answer_id': 7303433, 'author': 'Luke Quinane', 'author_id': 18437, 'author_profile': 'https://Stackoverflow.com/users/18437', 'pm_score': 7, 'selected': False, 'text': '<p>You could use <a href="https://github.com/twall/jna" rel="noreferrer">JNA</a>. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:</p>\n\n<h2>Windows</h2>\n\n<p>Make sure you have <code>jna-platform.jar</code> then:</p>\n\n<pre><code>int pid = Kernel32.INSTANCE.GetCurrentProcessId();\n</code></pre>\n\n<h2>Unix</h2>\n\n<p>Declare:</p>\n\n<pre><code>private interface CLibrary extends Library {\n    CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);   \n    int getpid ();\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>int pid = CLibrary.INSTANCE.getpid();\n</code></pre>\n\n<hr>\n\n<h1>Java 9</h1>\n\n<p>Under Java 9 the new <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html" rel="noreferrer">process API</a> can be used to get the current process ID. First you grab a handle to the current process, then query the PID:</p>\n\n<pre><code>long pid = ProcessHandle.current().pid();\n</code></pre>\n'}, {'answer_id': 7309009, 'author': 'Jared', 'author_id': 928992, 'author_profile': 'https://Stackoverflow.com/users/928992', 'pm_score': 3, 'selected': False, 'text': '<p>The latest I have found is that there is a <em>system property</em> called <code>sun.java.launcher.pid</code> that is available at least on linux.  My plan is to use that and if it is not found to use the <code>JMX bean</code>.</p>\n'}, {'answer_id': 7690178, 'author': 'Martin', 'author_id': 66981, 'author_profile': 'https://Stackoverflow.com/users/66981', 'pm_score': 5, 'selected': False, 'text': '<p>The following method tries to extract the PID from <code>java.lang.management.ManagementFactory</code>:</p>\n\n<pre><code>private static String getProcessId(final String fallback) {\n    // Note: may fail in some JVM implementations\n    // therefore fallback has to be provided\n\n    // something like \'&lt;pid&gt;@&lt;hostname&gt;\', at least in SUN / Oracle JVMs\n    final String jvmName = ManagementFactory.getRuntimeMXBean().getName();\n    final int index = jvmName.indexOf(\'@\');\n\n    if (index &lt; 1) {\n        // part before \'@\' empty (index = 0) / \'@\' not found (index = -1)\n        return fallback;\n    }\n\n    try {\n        return Long.toString(Long.parseLong(jvmName.substring(0, index)));\n    } catch (NumberFormatException e) {\n        // ignore\n    }\n    return fallback;\n}\n</code></pre>\n\n<p>Just call <code>getProcessId("&lt;PID&gt;")</code>, for instance.</p>\n'}, {'answer_id': 12066696, 'author': 'Brad Mace', 'author_id': 446591, 'author_profile': 'https://Stackoverflow.com/users/446591', 'pm_score': 6, 'selected': False, 'text': '<p>Here\'s a backdoor method which <em>might</em> not work with all VMs but should work on both linux and windows (<a href="http://boxysystems.com/index.php/java-tip-find-process-id-of-running-java-process/" rel="noreferrer">original example here</a>):</p>\n\n<pre><code>java.lang.management.RuntimeMXBean runtime = \n    java.lang.management.ManagementFactory.getRuntimeMXBean();\njava.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");\njvm.setAccessible(true);\nsun.management.VMManagement mgmt =  \n    (sun.management.VMManagement) jvm.get(runtime);\njava.lang.reflect.Method pid_method =  \n    mgmt.getClass().getDeclaredMethod("getProcessId");\npid_method.setAccessible(true);\n\nint pid = (Integer) pid_method.invoke(mgmt);\n</code></pre>\n'}, {'answer_id': 17348465, 'author': 'Espinosa', 'author_id': 1185845, 'author_profile': 'https://Stackoverflow.com/users/1185845', 'pm_score': 2, 'selected': False, 'text': '<p>This is the code JConsole, and potentially jps and VisualVM uses. It utilizes classes from\n<code>sun.jvmstat.monitor.*</code> package, from <code>tool.jar</code>.</p>\n\n<pre><code>package my.code.a003.process;\n\nimport sun.jvmstat.monitor.HostIdentifier;\nimport sun.jvmstat.monitor.MonitorException;\nimport sun.jvmstat.monitor.MonitoredHost;\nimport sun.jvmstat.monitor.MonitoredVm;\nimport sun.jvmstat.monitor.MonitoredVmUtil;\nimport sun.jvmstat.monitor.VmIdentifier;\n\n\npublic class GetOwnPid {\n\n    public static void main(String[] args) {\n        new GetOwnPid().run();\n    }\n\n    public void run() {\n        System.out.println(getPid(this.getClass()));\n    }\n\n    public Integer getPid(Class&lt;?&gt; mainClass) {\n        MonitoredHost monitoredHost;\n        Set&lt;Integer&gt; activeVmPids;\n        try {\n            monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));\n            activeVmPids = monitoredHost.activeVms();\n            MonitoredVm mvm = null;\n            for (Integer vmPid : activeVmPids) {\n                try {\n                    mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));\n                    String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);\n                    if (mainClass.getName().equals(mvmMainClass)) {\n                        return vmPid;\n                    }\n                } finally {\n                    if (mvm != null) {\n                        mvm.detach();\n                    }\n                }\n            }\n        } catch (java.net.URISyntaxException e) {\n            throw new InternalError(e.getMessage());\n        } catch (MonitorException e) {\n            throw new InternalError(e.getMessage());\n        }\n        return null;\n    }\n}\n</code></pre>\n\n<p>There are few catches:</p>\n\n<ul>\n<li>The <code>tool.jar</code> is a library distributed with Oracle JDK but not JRE! </li>\n<li>You cannot get <code>tool.jar</code> from Maven repo; configure it with Maven is a bit tricky</li>\n<li>The <code>tool.jar</code> probably contains platform dependent (native?) code so it is not easily \n distributable</li>\n<li>It runs under assumption that all (local) running JVM apps are "monitorable". It looks like\n that from Java 6 all apps generally are (unless you actively configure opposite)</li>\n<li>It probably works only for Java 6+</li>\n<li>Eclipse does not publish main class, so you will not get Eclipse PID easily\nBug in MonitoredVmUtil?</li>\n</ul>\n\n<p>UPDATE: I have just double checked that JPS uses this way, that is Jvmstat library (part of tool.jar). So there is no need to call JPS as external process, call Jvmstat library directly as my example shows. You can aslo get list of all JVMs runnin on localhost this way.\nSee JPS <a href="http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/tools/jps/Jps.java/?v=source" rel="nofollow noreferrer">source code</a>:</p>\n'}, {'answer_id': 19091039, 'author': 'Subhash', 'author_id': 864111, 'author_profile': 'https://Stackoverflow.com/users/864111', 'pm_score': -1, 'selected': False, 'text': '<p>This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux</p>\n\n<pre><code>netstat -tupln | grep portNumber\n</code></pre>\n'}, {'answer_id': 21702291, 'author': 'tomsv', 'author_id': 246622, 'author_profile': 'https://Stackoverflow.com/users/246622', 'pm_score': 2, 'selected': False, 'text': '<p>Based on Ashwin Jayaprakash\'s <a href="https://stackoverflow.com/a/3134967/246622">answer</a> (+1)\nabout the Apache 2.0 licensed <code>SIGAR</code>, here is how I use it to get only the PID of the current process:</p>\n\n<pre><code>import org.hyperic.sigar.Sigar;\n\nSigar sigar = new Sigar();\nlong pid = sigar.getPid();\nsigar.close();\n</code></pre>\n\n<p>Even though it does not work on all platforms, it does work on <a href="https://support.hyperic.com/display/SIGAR/Home#Home-overview" rel="nofollow noreferrer">Linux, Windows, OS X and various Unix platforms as listed here</a>.</p>\n'}, {'answer_id': 28981466, 'author': 'kervin', 'author_id': 16549, 'author_profile': 'https://Stackoverflow.com/users/16549', 'pm_score': 1, 'selected': False, 'text': '<p>You can try <code>getpid()</code> in <a href="https://github.com/jnr/jnr-posix" rel="nofollow">JNR-Posix</a>.  </p>\n\n<p>It has a Windows POSIX wrapper that calls getpid() off of libc.</p>\n'}, {'answer_id': 31037052, 'author': 'Brandon Heck', 'author_id': 1579393, 'author_profile': 'https://Stackoverflow.com/users/1579393', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is an old thread, but I wanted to call out that API for getting the PID (as well as other manipulation of the Java process at runtime) is being added to the Process class in JDK 9: <a href="http://openjdk.java.net/jeps/102" rel="nofollow">http://openjdk.java.net/jeps/102</a></p>\n'}, {'answer_id': 31072610, 'author': 'ZhekaKozlov', 'author_id': 706317, 'author_profile': 'https://Stackoverflow.com/users/706317', 'pm_score': 4, 'selected': False, 'text': '<p>Since Java 9 there is a method Process.getPid() which returns the native ID of a process:</p>\n\n<pre><code>public abstract class Process {\n\n    ...\n\n    public long getPid();\n}\n</code></pre>\n\n<p>To get the process ID of the current Java process one can use the <code>ProcessHandle</code> interface:</p>\n\n<pre><code>System.out.println(ProcessHandle.current().pid());\n</code></pre>\n'}, {'answer_id': 33573952, 'author': 'PartialData', 'author_id': 2989079, 'author_profile': 'https://Stackoverflow.com/users/2989079', 'pm_score': -1, 'selected': False, 'text': '<p>Here is my solution:</p>\n\n<pre><code>public static boolean isPIDInUse(int pid) {\n\n        try {\n\n            String s = null;\n            int java_pid;\n\n            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();\n            java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));\n\n            if (java_pid == pid) {\n                System.out.println("In Use\\n");\n                return true;\n            }\n        } catch (Exception e) {\n            System.out.println("Exception:  " + e.getMessage());\n        }\n        return false;\n    }\n</code></pre>\n'}, {'answer_id': 33837794, 'author': 'Florin T.', 'author_id': 5000738, 'author_profile': 'https://Stackoverflow.com/users/5000738', 'pm_score': 3, 'selected': False, 'text': '<p>In Scala:</p>\n\n<pre><code>import sys.process._\nval pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong\n</code></pre>\n\n<p>This should give you a workaround on Unix systems until Java 9 will be released.\n(I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)</p>\n'}, {'answer_id': 38122943, 'author': 'AntiTiming', 'author_id': 4635513, 'author_profile': 'https://Stackoverflow.com/users/4635513', 'pm_score': 3, 'selected': False, 'text': '<p>For completeness there is a wrapper in <strong>Spring Boot</strong> for the </p>\n\n<pre><code>String jvmName = ManagementFactory.getRuntimeMXBean().getName();\nreturn jvmName.split("@")[0];\n</code></pre>\n\n<p>solution. If an integer is required, then this can be summed up to the one-liner:</p>\n\n<pre><code>int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);\n</code></pre>\n\n<p>If someone uses Spring boot already, she/he might use <em>org.springframework.boot.ApplicationPid</em></p>\n\n<pre><code>ApplicationPid pid = new ApplicationPid();\npid.toString();\n</code></pre>\n\n<p>The toString() method prints the pid or \'???\'.</p>\n\n<p>Caveats using the ManagementFactory are discussed in other answers already.</p>\n'}, {'answer_id': 39744535, 'author': 'JaskeyLam', 'author_id': 2087628, 'author_profile': 'https://Stackoverflow.com/users/2087628', 'pm_score': 3, 'selected': False, 'text': '<pre><code>public static long getPID() {\n    String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();\n    if (processName != null &amp;&amp; processName.length() &gt; 0) {\n        try {\n            return Long.parseLong(processName.split("@")[0]);\n        }\n        catch (Exception e) {\n            return 0;\n        }\n    }\n\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 43399977, 'author': 'markus', 'author_id': 2250186, 'author_profile': 'https://Stackoverflow.com/users/2250186', 'pm_score': 4, 'selected': False, 'text': '<pre><code>java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]\n</code></pre>\n'}, {'answer_id': 48959178, 'author': 'mrsrinivas', 'author_id': 1592191, 'author_profile': 'https://Stackoverflow.com/users/1592191', 'pm_score': 3, 'selected': False, 'text': "<p>I am adding this, in addition to other solutions.</p>\n<h2>with Java 10, to get <code>process id</code></h2>\n<pre><code>final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();\nfinal long pid = runtime.getPid();\nout.println(&quot;Process ID is '&quot; + pid);\n</code></pre>\n"}, {'answer_id': 52130795, 'author': 'Armin Bu', 'author_id': 2587809, 'author_profile': 'https://Stackoverflow.com/users/2587809', 'pm_score': 0, 'selected': False, 'text': '<p>I found a solution that may be a bit of an edge case and I didn\'t try it on other OS than Windows 10, but I think it\'s worth noticing.</p>\n\n<p>If you find yourself working with <a href="https://github.com/eclipsesource/J2V8" rel="nofollow noreferrer">J2V8</a> and nodejs, you can run a simple javascript function returning you the pid of the java process.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>public static void main(String[] args) {\n    NodeJS nodeJS = NodeJS.createNodeJS();\n    int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\\n");\n    System.out.println(pid);\n    nodeJS.release();\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/35842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3583/']