PidProcessDestroyer.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package com.primeton.datainsight.task;
  2. import org.apache.commons.exec.ProcessDestroyer;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.lang.reflect.Field;
  6. /**
  7. * <pre>
  8. *
  9. * Created by zhaopx.
  10. * User: zhaopx
  11. * Date: 2019/6/3
  12. * Time: 18:40
  13. *
  14. * </pre>
  15. *
  16. * @author zhaopx
  17. */
  18. public class PidProcessDestroyer implements ProcessDestroyer {
  19. public static final String PID = "pid";
  20. private static Logger logger = LoggerFactory.getLogger(PidProcessDestroyer.class);
  21. final String taskId;
  22. /**
  23. * 进程 ID, 如果没有获取到取值 -1
  24. */
  25. private int processId = -1;
  26. /**
  27. * 根据 TaskId 更新 Task 状态
  28. * @param taskId
  29. */
  30. public PidProcessDestroyer(String taskId) {
  31. this.taskId = taskId;
  32. }
  33. /**
  34. * 获取子进程内 Process PID
  35. *
  36. * @param process
  37. * @return
  38. */
  39. public static int getProcessId(Process process) {
  40. int processId = 0;
  41. try {
  42. Field f = process.getClass().getDeclaredField(PID);
  43. f.setAccessible(true);
  44. processId = f.getInt(process);
  45. } catch (Throwable e) {
  46. logger.error(e.getMessage(), e);
  47. }
  48. return processId;
  49. }
  50. @Override
  51. public boolean add(Process process) {
  52. processId = getProcessId(process);
  53. logger.info("task {} state RUNNING pid {}", taskId, processId);
  54. //taskHistService.updateTaskPid(taskId, "RUNNING", processId);
  55. return true;
  56. }
  57. @Override
  58. public boolean remove(Process process) {
  59. return true;
  60. }
  61. @Override
  62. public int size() {
  63. return 1;
  64. }
  65. public int getPid() {
  66. return processId;
  67. }
  68. }