package com.nms.server.thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;

import org.apache.log4j.Logger;

import com.nms.server.common.Constants;

public class WritePidThread implements Runnable{

	@Override
	public void run() {
//		Thread.currentThread().setName("写PID线程");
		Thread.currentThread().setName("Write the PID thread");
		Logger logger = Logger.getLogger(WritePidThread.class);
		
		/* 获取程序运行PID */
		String path = new File(Constants.SYSTEM_PATH).getParent()+File.separator+Constants.COMMON_TEMP_DIR+File.separator+Constants.COMMON_RUNTIME_PID_FILE;
		String name = ManagementFactory.getRuntimeMXBean().getName();
		logger.info("当前程序PID:>"+(name.split("@")[0]));
		
		/* 判断系统类型是否写文件 */
		String os =  System.getProperty("os.name");
		if(os!=null && !os.toLowerCase().startsWith("windows")){
			logger.info("非Windows系统 结束执行");
			return ;
		}
		
		/* 获取输出文件并检查文件路径是否存在 */
		File file = new File(path);
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		
		/* 将PID写入文件 */
		FileOutputStream oStream = null;
		try {

			oStream = new FileOutputStream(path,false);

			oStream.write(name.split("@")[0].getBytes());

			oStream.flush();

			logger.info("写PID完成:>"+file.getAbsolutePath());
		} catch (IOException e) {
			logger.error("Write PID failure", e);
		}finally{
			try {
				if(oStream!=null) 
					oStream.close();
				oStream = null;
			} catch (IOException e) {
				logger.error("", e);
			}
			logger.info("线程关闭");
		}
	}
	public static void main(String [] args) {
		new Thread(new WritePidThread()).start();
	}
	public static void pl (Object obj) {
		System.out.println(obj==null?null:obj.toString());
	}
}
