【发布时间】:2014-03-20 19:40:19
【问题描述】:
更新(2014 年 3 月 20 日下午 5:11 EST):添加了编写“GotHere0.txt”的代码。 Gothere0、1、2、3 看起来都很好。 Gothere4 没有出现。
请注意 - 这不是重复的 - 它与我发现的所有现有线程都有非常细微的差异。
要求:
- 在 Windows Server 2008 R2 中,从在本地系统帐户下运行的 Windows 服务启动控制台应用程序
- 控制台应用程序内部的代码写入 SQL 数据库,并将文件写入驱动器,但不需要用户输入(也不需要查看控制台本身或与控制台本身交互)。我们所需要的只是来自控制台应用程序的代码来执行。
- 这应该在服务器启动时工作,无需用户登录。
目前的结果:
Process.Start(sInfo) 就像一切都成功一样完成。不抛出异常。返回进程 ID > 0。但是,很明显 testapp.exe 中的代码实际上并没有执行。有谁知道我该如何解决这个问题?谢谢!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace TestService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.IO.File.WriteAllText(@"c:\temp\GotHere0.txt", "");
System.Threading.Tasks.Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning);
}
protected override void OnStop()
{
ContinueRunning = false;
}
public static bool ContinueRunning = true;
public void Run()
{
System.IO.File.WriteAllText(@"c:\temp\GotHere1.txt", "");
while (ContinueRunning)
{
try
{
List<string> args = new List<string>();
args.Add("Test");
StartApp(@"c:\temp\testapp.exe", args);
}
catch (Exception)
{ }
if (ExitEarly()) return;
}
}
private static void StartApp(string exePath, List<string> args)
{
try
{
System.IO.File.WriteAllText(@"c:\temp\GotHere2.txt", "");
ProcessStartInfo sInfo = new ProcessStartInfo();
sInfo.FileName = exePath;
sInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(exePath);
sInfo.Arguments = string.Join(" ", args);
sInfo.CreateNoWindow = false;
Process runningProcess = Process.Start(sInfo);
string message = "";
if (runningProcess!=null)
{
message = runningProcess.Id.ToString();
}
System.IO.File.WriteAllText(@"c:\temp\GotHere3.txt", message);
}
catch (Exception exc)
{
System.IO.File.WriteAllText(@"c:\temp\GotHere4.txt", exc.Message);
}
}
private static bool ExitEarly()
{
// Sleep for a total of 60 seconds, and return if "OnStop" is called.
for (int i = 0; i < 600; i++)
{
System.Threading.Thread.Sleep(100);
if (!ContinueRunning) return true;
}
return false;
}
}
}
这里是testapp.exe的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
if (args == null || args.Length == 0)
{
sb.AppendLine("NO arguments were passed.");
}
else
{
foreach (string arg in args)
{
sb.AppendLine("Arg: [" + arg + "]");
}
}
System.IO.File.WriteAllText("helloworld.txt", sb.ToString());
}
}
}
【问题讨论】:
-
您是否尝试过使用 normal(不是默认服务)用户帐户启动服务,例如你的,然后看看它是否有效?
-
如何明确没有代码实际执行?你如何验证程序没有运行?
-
控制台应用程序所做的只是将文本文件“helloworld.txt”写入同一文件夹。也尝试将其写入 c:\temp。两者都不起作用。注意:所有这些在我的 Windows 8 机器上都可以正常工作。我开始怀疑这是 Windows Server 2008 R2 机器上的组策略设置。有人知道可能会影响到这一点的组策略吗?
-
您在哪个用户下运行服务?
-
感谢 Lasse 的回复。该服务在“本地系统”下运行
标签: c# windows-services console-application windows-server-2008-r2 process.start