Wait for child process to start

  • Thread starter Thread starter NavnathK
  • Start date Start date
N

NavnathK

Guest
Hello,

I have a Windows Service and I want to run a child process from within this Windows Service. I am using C# Process class and its StartInfo property to start the process.

However, it is not sure to me whether the child process is initialized and started successfully. So, I want to wait until the child process has been started successfully. FYI, the child process is a small server with no UI.

I don't want to use Thread.Sleep(). My child process do not have any UI. So, as per the documentation, I can not use WaitForInputIdle method. I also tried to use ManagementEventWatcher, but parent process [Windows Service] does not wait for child process because http request is being sent before the child process is started.

Here is my code to start the child process:

public void startReqtifyInstance()
{
//Read port number from INI file
int delayBeforeClosing = INIFileHandler.IniReadValue("ExternalServer", "DelayBeforeClosing");
setPortNo(DataHelper.getPortNumberForNewReqtifyInstance());

Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = DataHelper.getReqtifyPath();
proc.StartInfo.Arguments = "-http " + portNo + " -timeout " + DataHelper.getDelayBeforeClosingSession()
+" -logfile " + @ServerConfig.LOG_FILE_PATH;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;

try
{
var queryString =
"SELECT TargetInstance " +
"FROM __InstanceCreationEvent WITHIN 1 " +
"WHERE TargetInstance ISA 'Win32_Process' " +
"AND TargetInstance.Name LIKE 'reqtify.exe'";

var scope = @"\\.\root\CIMV2";

var watcher = new ManagementEventWatcher(scope, queryString);
watcher.EventArrived += (sender, e) => watcher_EventArrived(sender, e, proc.Id);

watcher.Start();

proc.Start();
}
catch (Exception e)
{
Console.WriteLine("Error {0}", e.ToString());
}
}

void watcher_EventArrived(object sender, EventArrivedEventArgs e,int processId)
{
Console.WriteLine("Reqtify has been started");
setReqtifyProcessId(processId);
}


I hope you understand the code.

Please give me some advice on this or any other elegant solution.

Thank you in advance!

Navnath

Continue reading...
 
Back
Top