本次主要讨论linux底下java对进程是否存在进行判断,以及java如何执行Linux脚本和命令
java要执行Linux脚本首先得获取java的运行环境runtime
/** * 执行linux命令 * @auther liduote * 2017-2-21 下午04:41:28 * @param runtime * @throws IOException */ public static void execCMD(Runtime runtime) throws IOException { runtime.exec("ls -al"); }tips:ps 命令使用方法 ps [-aAcdefHjlmNVwy][acefghLnrssTuvxX][-C <指令名称>][-g <群组名称>] [-G <群组识别码>][-p <进程识别码>][p <进程识别码>][-s <阶段作业>] [-t <终端机编号>][t <终端机编号>][-u <用户识别码>][-U <用户识别码>] [U <用户名称>][-<进程识别码>][–cols <每列字符数>] [–columns <每列字符数>][–cumulative][–deselect][–forest] [–headers][–help][– info][–lines <显示列数>][–no-headers] [–group <群组名称>][-Group <群组识别码>][–pid <进程识别码>] [–rows <显示列数>][–sid <阶段作业>][–tty <终端机编号>] [–user <用户名称>][–User <用户识别码>][–version] [–width <每列字符数>]
#假如查询MySQL$ ps -C mysqld -f --columns=200-------------------------------UID PID PPID C STIME TTY TIME CMDpolkitd 24995 11152 0 Jan12 ? 00:21:22 mysqld --init-file=/tmp/mysql-first-time.sql所以我们通过java代码的写法是
public boolean isExistPRocess() throws IOException { String command = "ps -C mysqld -f --cols=200"; String program = "mysqld --init-file=/tmp/mysql-first-time.sql"; boolean isExistProcess = false; Process process = Runtime.getRuntime().exec(command); InputStream in = process.getInputStream(); InputStreamReader is = new InputStreamReader(in); BufferedReader read = new BufferedReader(is); String line = ""; while((line = read.readLine()) != null) { if(line.indexOf(program) >= 0) { isExistProcess = true; break; } } //关闭流 in.close(); is.close(); read.close(); process.destroy(); return isExistProcess; }新闻热点
疑难解答