windows下的cmd命令与shell使用方法

常用cmd命令

tasklist  //查询全部进程
taskkill /pid 313592  -f  //杀死一个进程一个进程
tasklist|find /i "explorer.exe" //根据进程名称判断是否存在
tasklist|findstr 3120 //根据pid判断进程是否存在
D:/BaiduYunDownload/WinRAR/WinRAR.exe a d:/abc.rar d:/test.txt  //压缩text.txt文件

应用:找到占用了端口的进程将其杀掉

//查看端口占用情况
netstat  -aon|findstr  "8080"
//查看是哪个进程占用
tasklist|findstr "your_pid"
//Ctrl+shift+Ecs 详细信息找出相应进程名和pid将其杀掉

windows下使用shell

安装cygwin,cygwin官网cygwin的安装

安装完成后输入以下命令查看home所在的目录。

cygpath -dm "`pwd`"
输出:C:/cygwin64/home

思考

如何通过java代码来执行shell脚本呢

public static boolean isWindows() {
	return System.getProperty("os.name").startsWith("Windows");
}

public static Long executeShell(String commandStr) throws Exception {
        Long pid = null;
        String[] commandArr = new String[]{"C:/cygwin64/bin/sh", "-c", commandStr};
	//String[] commandArr = new String[]{"sh", "-c", commandStr};
        //if (isWindows()) {
        //    commandStr = "tasklist|findstr " + pid;
        //    commandArr = new String[]{"cmd.exe", "/C", commandStr};
        //}
        Process process = Runtime.getRuntime().exec(commandArr);
        if (process != null) {
            //获取进程id
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handl = f.getLong(process);
            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handl));
            pid = Long.valueOf(kernel.GetProcessId(handle));
            process.waitFor();
//            process.destroy();
        }
     return pid;
} 

以上代码可以在直接将要执行的命令作为参数传入



  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值