0

I am running Phantomjs.exe in the background. I would like to keep this process running all the time. When it's time to use this process (on button click) I would like to check if the process is running. If it is running I would like to use that process. If it is not running, I will start a new process.

I've found out how to check if the process is running and how to start a new process in that case. But I don't know how to connect C# variable with already running process? (so there is no need to start - stop process each time, which takes a lot of time)

My code:

public bool IsProcessOpen(string name)
{
  foreach (Process clsProcess in Process.GetProcesses())
  {
    if (clsProcess.ProcessName.Contains(name))
    {
      return true;
    }
  }
  return false;
}

private void button1_Click(object sender, EventArgs e)
    {
        PhantomJSOptions options = new PhantomJSOptions();
        PhantomJSDriver driver = null;
        bool phantomOpened = IsProcessOpen("Phantomjs");

      if(!phantomOpened)
     {
        PhantomJSDriver driver = new PhantomJSDriver(options);
      }
      else //set PhantomJSDriver to running exe
     {
     }


}
FrenkyB
  • 6,625
  • 14
  • 67
  • 114

1 Answers1

0

I think there are some misconceptions here:

  • Checking for a process with a given name cannot ensure you're detecting the right process. I can rename Notepad to PhantomJS and you'll detect the wrong one.

  • You can't simply access another process's memory. Each process has its own virtual memory that is protected from other processes.

Solutions are:

  • for detecting a running process, use a named Mutant (Mutex). If you find it, the process is running, if not, start the process. Give it a GUID or other name that can hardly be guessed or reused.
  • for exchanging data between two processes use a named pipe or shared memory (general concepts, language independent) or an IPC channel (.NET specific)

Make yourself failiar with those concepts and you'll probably find code examples here on SO.

Alternate solutions I would not recommend:

  • Sending a Window message to the other process might not work reliably in case multiple desktops are used.
  • Implementing a debugger that attaches to the process and ... well, do difficult stuff.
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • Is there really no other (easier) way? Let's say if I create a simple exe with only one method and then run it. The only thing I want is to call that simple method from another application. Do I really have to use IPC / named pipes for this? – FrenkyB Aug 30 '17 at 18:13
  • @FrenkyB: if it's that simple, why not implement the method in your code directly? Or load the EXE as an assembly into your application and call the method there... – Thomas Weller Aug 30 '17 at 18:18