View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.util;
19  
20  import java.io.IOException;
21  import java.lang.management.ManagementFactory;
22  import java.util.List;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  
28  /**
29   * Process related utilities.
30   */
31  @InterfaceAudience.Private
32  public final class ProcessUtils {
33    private static Log LOG = LogFactory.getLog(ProcessUtils.class);
34  
35    private ProcessUtils() { }
36  
37    public static Integer getPid() {
38      // JVM_PID is exported by bin/hbase run script
39      String pidStr = System.getenv("JVM_PID");
40  
41      // in case if it is not set correctly used fallback from mxbean which is implementation specific
42      if (pidStr == null || pidStr.trim().isEmpty()) {
43        String name = ManagementFactory.getRuntimeMXBean().getName();
44        if (name != null) {
45          int idx = name.indexOf("@");
46          if (idx != -1) {
47            pidStr = name.substring(0, name.indexOf("@"));
48          }
49        }
50      }
51      try {
52        if (pidStr != null) {
53          return Integer.valueOf(pidStr);
54        }
55      } catch (NumberFormatException nfe) {
56        // ignore
57      }
58      return null;
59    }
60  
61    public static Process runCmdAsync(List<String> cmd) {
62      try {
63        LOG.info("Running command async: " + cmd);
64        return new ProcessBuilder(cmd).inheritIO().start();
65      } catch (IOException ex) {
66        throw new IllegalStateException(ex);
67      }
68    }
69  }