.Net执行cmd命令
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;
namespace WebForm
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(ExeCommand("ping www.126.com"));
}
public string ExeCommand(string commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
strOutput = e.Message;
}
return strOutput;
}
}
}
WaitForExit
程序里我使用Process类启动命令行,执行批处理文件 'Create.cmd'(当我手工将此文件拖入命令行执行时,一切正常)。C#程序代码类似如下,其中batchFilePath变量为批处理文件全路径:

Code
m_BasicDataProc = new Process();
m_BasicDataProc.StartInfo.FileName = "cmd.exe";
m_BasicDataProc.StartInfo.CreateNoWindow = false;
m_BasicDataProc.StartInfo.UseShellExecute = false;
m_BasicDataProc.StartInfo.RedirectStandardOutput = true;
m_BasicDataProc.StartInfo.RedirectStandardInput = true;
m_BasicDataProc.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFilePath);
m_BasicDataProc.Start();
string batchFileName = Path.GetFileName(batchFilePath);
StreamWriter inputStream = m_BasicDataProc.StandardInput;
inputStream.WriteLine(batchFileName);
inputStream.Close();
m_BasicDataProc.WaitForExit();
m_BasicDataProc.EnableRaisingEvents = true;
批处理文件'Create.cmd'调用'sqlplus'来执行若干个sql文件:
//===================================================
echo Tables on level 0:
if exist InstallScripts\Create01.sql (
echo bas
sqlplus %1/%2@%3 @InstallScripts\Create01.sql | %HideSQLPlusRows%
REM > Logs\Create_%1.txt
)
if exist InstallScripts\Create02.sql (
......
//===================================================
出现的问题是程序运行到'm_BasicDataProc.WaitForExit();'这一行时就阴塞不动.
搞 了两天,最后发现原因是出现了死锁。由于标准输出流被重定向,而Process.StandardOutput的缓冲大小是有限制的(据说是4k),所以 当缓冲满了的时候(执行上面的批处理文件有很多的输出),子进程(cmd.exe)会等待主进程(C# App)读取并释放此缓冲,而主进程由于调用了WaitForExit()方法,则会一进等待子进程退出,最后形成死锁。
了解了原因后,有3种方法可以解决问题:
1)修改批处理文件,在调用sqlplus时将输出指定到一个log文件,这样被生定向到StandardOutput中的内容相对就少,不容易造成问题:
//===================================================
echo Tables on level 0:
if exist InstallScripts\Create01.sql (
echo bas
sqlplus %1/%2@%3 @InstallScripts\Create01.sql | %HideSQLPlusRows% > Logs\Create_%1.txt
)
......
//===================================================
2)修改C#代码,将'm_BasicDataProc.StartInfo.RedirectStandardOutput = false;',这样所有的输出会在命令行屏幕上直接输出,不会重定向到标准输出流中。
3) 修改C#代码,在'm_BasicDataProc.WaitForExit();'前添加 'm_BasicDataProc.BeginOutputReadLine();' 或 'm_BasicDataProc.StandardOutput.ReadToEnd();',通过读取输出流,以便释放相应的缓冲。
.Net执行cmd命令的更多相关文章
- JAVA之执行cmd命令
感言在前:时隔好久没有更新博客园了,忙东忙西也没忙出个什么之所以然来.回首过去一两个月,只能用“疲倦”两个字来形容,而且是身心疲惫.每天11.12个小时的工作我都没觉得烦,但是总是想克服却又很难克服的 ...
- [转]Delphi执行CMD命令
今天看到有人在问用代码执行CMD命令的问题,就总结一下用法,也算做个备忘. Delphi中,执行命令或者运行一个程序有2个函数,一个是winexec,一个是shellexecute.这两个大家应该都见 ...
- C# 执行CMD 命令
/// <summary> /// 执行CMD 命令 /// </summary> /// <param name="strCommand">命 ...
- C# 执行CMD命令的方法
/// <summary> /// 执行CMD命令 /// </summary> /// <param name="str"></para ...
- 如何使用Java执行cmd命令
用JAVA代码实现执行CMD命令的方法! Runtime rt = Runtime.getRuntime(); Process p = rt.exec(String[] cmdarray); ...
- java执行cmd命令并获取输出结果
1.java执行cmd命令并获取输出结果 import java.io.BufferedReader; import java.io.InputStreamReader; import org.apa ...
- Java 调用并执行cmd命令
cmd java 调用 执行 概要: Java 调用并执行cmd命令 Java | 复制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 2 ...
- Atitit.执行cmd 命令行 php
Atitit.执行cmd 命令行 php 1. 执行cmd 命令行,调用系统命令的基础 1 1.1. 实际执行模式 1 1.2. 空格的问题 1 1.3. 中文路径的问题,程序文件读取编码设置 1 1 ...
- node执行cmd命令方法
var cmd='tasklist';//获取 子进程模块的exec方法,用于执行cmd命令var exec = require('child_process').exec; //运行 定义的cmd命 ...
- java中执行cmd命令
一.java执行cmd命令的三种方式:http://www.jb51.net/article/80829.htm 参考:https://www.cnblogs.com/zhufu9426/p/7928 ...
随机推荐
- C语言 · 字符删除
算法训练 字符删除 时间限制:1.0s 内存限制:512.0MB 问题描述 编写一个程序,先输入一个字符串str(长度不超过20),再输入单独的一个字符ch,然后程序会把字符串str ...
- LINUX任务(jobs)详解
LINUX任务(jobs)详解 在用管理员执行一个命令后,用Ctrl+Z把命令转移到了后台.导致无法退出root的. 输入命令:exit终端显示:There are stopped jobs. 解决方 ...
- c#获取网页代码、数据、资源
//WebClient取网页源码 private string GetHtmlSource(string Url) { try { System.Net.WebClient wc = new Syst ...
- 防简单攻击iptables策略
#!/bin/sh IPTABLES=/sbin/iptables # clear $IPTABLES -F # if pkg type is allow, then accept #$IPTABLE ...
- android 中解析json格式数据
本文来自http://tonysun3544.iteye.com/category/188238 package com.tony.json; import android.app.Activity; ...
- ubuntu16.04安装workbench
sudo dpkg -i mysql-workbench-community-6.3.10-1ubuntu16.04-amd64.deb 报错: Selecting previously unsele ...
- 使用OpenOffice.org将各类文档转为PDF
http://blog.zhaojie.me/2010/05/convert-document-to-pdf-via-openoffice.html ————————————————————————— ...
- 图示 Smart-Art
在PPT中,图示有两个作用,一是将对象间的逻辑关系视觉化,使文字承载的信息一目了然; 二是打破呆板的页面版式,让枯燥的文本变得更有魅力. 比较聪明的办法是在Sma吨Art生成图形的基础上继续编辑,使其 ...
- ES6之数组操作
es6中对于数组操作添加了4种方法: 1.map —— 映射(一个对应一个) 2.reduce —— 汇总(多个出来一个) 3.filter —— 过滤 4.forEach —— 迭代/循环. 1.m ...
- 安装OpenSSL缺失Microsoft Visual C++ 2008 Redistributables的解决方案
在安装OpenSSL的时候通常会提示以下错误: "The Win32 OpenSSL Installation Project setup has detected that the fol ...