1

I am executing the Cmd commands using C# console application by creating new process. facing issue in killing the process on WaitforExit.

Basically I want to terminate the command execution on waitforexit. Please help.

Code:

    string Command = "perl Simple_File_Copy.pl"

    ProcessStartInfo procStartInfo = new ProcessStartInfo();
    procStartInfo.FileName = "cmd.exe";
    procStartInfo.Arguments = "/c " + Command + " & exit";
    procStartInfo.WorkingDirectory = ProcessDirectory;
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.RedirectStandardError = true;
    procStartInfo.RedirectStandardInput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = false;
    procStartInfo.WindowStyle = ProcessWindowStyle.Normal;

    Process process = Process.Start(procStartInfo);

      if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds)) //wait for 10 seconds
        {
            Console.WriteLine("TimeOut Exception");

            // the perl command still contiue its exeuction if I use any of 
below.
//Want to terminate the command line step at this stage
            process.Kill(); 
            process.CloseMainWindow();
            process.Close();
        }
Pradeep H
  • 592
  • 2
  • 7
  • 27

1 Answers1

1

Since your application is creating other processes, you'll need to kill the whole process tree (cmd is being killed in your example, but cmd is running another application which runs perl script and that's not getting killed). Sample Code to kill the whole tree:

Usage

KillProcessAndChildren(process.Id);

Method

/// <summary>
    /// Kill a process, and all of its children, grandchildren, etc.
    /// </summary>
    /// <param name="pid">Process ID.</param>
    private static void KillProcessAndChildren(int pid)
    {
        // Cannot close 'system idle process'.
        if (pid == 0)
        {
            return;
        }
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
          ("Select * From Win32_Process Where ParentProcessID=" + pid);
        ManagementObjectCollection moc = searcher.Get();
        foreach (ManagementObject mo in moc)
        {
            KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
        }
        try
        {
            Process proc = Process.GetProcessById(pid);
            proc.Kill();
        }
        catch (ArgumentException)
        {
            // Process already exited.
        }
    }

Reference: Kill process tree programmatically in C#

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40