Home > Blockchain >  Process Id is changed while running the process
Process Id is changed while running the process

Time:05-23

I am using System.Diagnostics in c#. My problem is I am using code for starting and killing the process in c# and it's working fine. But my question is my process id is changing in-between while running the process. Is that possible. If yes then how can I get the actual process id which I want to kill. I can't do it by name because I have multiple instance are running on different at a time and I want to kill only single instance on started port.

My code is :

Process p2 = new Process();
                    ProcessStartInfo processStartInfo2 =
                        new ProcessStartInfo(
                            unitoolLauncherExePath,
                            "options --port "   port);

  p2.StartInfo = processStartInfo2;
  p2.Start();
  System.Threading.Thread.Sleep(1000);
  int processId = p2.Id;

Now it will return something like 14823 and when I am trying to kill it it's changed.

Process[] _proceses = null;
            _proceses = Process.GetProcessesByName("UNIToolAPIServer");
            foreach (Process proces in _proceses)
            {
                if (proces.Id == processId)
                {                    
                    proces.Kill();                        
                }
                    
            }

But here nothing is killed because no process with the above id is fetched.

CodePudding user response:

No, the process id of a running process does not change while it is running.

If there is no process to kill with the process id of the process you started, it means either of two things:

  • The process has already exited before you obtain the process list.
  • The name of the process is not "UNIToolAPIServer".

CodePudding user response:

If you want to kill the created process you should keep the process-object and call the kill method on it. There should be no need to go thru all the processes in the system to find the started process. For example:

public class MyProcess{
  private Process myProcess;
  ...
  public void Start(){
    myProcess = new Process();
    var processStartInfo2 = new ProcessStartInfo(
                            unitoolLauncherExePath,
                            "options --port "   port);

    myProcess.StartInfo = processStartInfo2;
    myProcess.Start();
  }
  public void Kill(){
    if(myProcess != null && !myProcess.HasExited){
          myProcess.Kill();
     }
  }
}
   
  • Related