gpt4 book ai didi

c# - 调用批处理文件后服务在 WaitForExit 处挂起

转载 作者:IT王子 更新时间:2023-10-29 04:45:56 24 4
gpt4 key购买 nike

我有一项服务有时会调用批处理文件。批处理文件需要 5-10 秒来执行:

System.Diagnostics.Process proc = new System.Diagnostics.Process(); // Declare New Process
proc.StartInfo.FileName = fileName;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();

当我在控制台中运行相同的代码时,该文件确实存在并且代码有效。但是,当它在服务内部运行时,它会在 WaitForExit() 处挂起。我必须从进程中终止批处理文件才能继续。 (我确定该文件存在,因为我可以在进程列表中看到它。)

我该如何解决这个问题?

更新#1:

Kevin 的代码允许我获得输出。我的一个批处理文件仍然挂起。

"C:\EnterpriseDB\Postgres\8.3\bin\pg_dump.exe" -i -h localhost -p 5432 -U postgres -F p -a -D -v -f "c:\backupcasecocher\backupdateevent2008.sql" -t "\"public\".\"dateevent\"" "DbTest"

另一个批处理文件是:

"C:\EnterpriseDB\Postgres\8.3\bin\vacuumdb.exe" -U postgres -d DbTest

我检查了路径,postgresql 路径没问题。输出目录确实存在并且仍然在服务之外工作。有什么想法吗?

更新#2:

我为 proc.StartInfo.FileName 编写了“C:\EnterpriseDB\Postgres\8.3\bin\pg_dump.exe”,而不是批处理文件的路径,并将所有参数添加到proc.StartInfo.Arguments。结果没有变化,但我在进程窗口中看到了 pg_dump.exe。同样,这只发生在服务内部。

更新#3:

我已经使用管理员组中的用户运行该服务,但无济于事。我为服务的用户名和密码恢复了 null

更新#4:

我创建了一个简单的服务来在事件日志中写入跟踪并执行一个包含“dir”的批处理文件。它现在将卡在 proc.Start(); - 我尝试将帐户从 LocalSystem 更改为 User 并设置了管理员用户和密码,但仍然没有。

最佳答案

这是我用来执行批处理文件的:

proc.StartInfo.FileName                 = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;

proc.Start();

proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout * NO_MILLISECONDS_IN_A_SECOND *
NO_SECONDS_IN_A_MINUTE
);

errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();

outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();

我不知道这是否对你有用,但我没有挂起的问题。

关于c# - 调用批处理文件后服务在 WaitForExit 处挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/361097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com