1

I have an agent program that will launch multiple instance of the same executable. Each of those instances need to have an individual ID associated with them.

The agent retains a reference to the Process object that was used to load the instance, but I have to consider that the agent may be shut down and restarted without affecting the started instances.

Once the agent starts again, I need it to search the existing processes and rebind a reference to the processes.

How can I assign data to a process and retrieve it afterwards?

Right now, I am starting the process like this:

this.AttachedProcess = new Process()
{
    StartInfo = new ProcessStartInfo(filename)
};

And, later, I need to search for that process by calling Process.GetProcesses().

While I could use a command line argument to start the process (something like -instance XX) and read that command line using this answer, I'd like to know if there is another way to assign extra data to a process and retrieve it later.

Community
  • 1
  • 1
Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101

2 Answers2

2

You could save the Process.Id of the processes you create in a file.
Upon startup you read that file and check if those processes still are started and check that the filename matches (if the system has been restarted some other processes might have got those ids)

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
2

You could create a serializable class ProcessInfo that stores the process ID and any other information you want to associate with the process. When the agent shuts down (such as if the service stops, or when it gets disposed, or a closing event gets fired, etc) have it serialize the process info to a file. When it starts up again, it should check for and read in the process info file, which will essentially restore the agent to the state it was in just before it was shut down.

The main idea here is that the agent should be maintaining this information, not Windows or the individual processes that are running. Requesting auxiliary data from a process requires COM, WCF, or some other messaging service, and this is overkill for the kind of interaction you're talking about.

See the System.Runtime.Serialization namespace, particularly the DataContractSerializer class.

Jake
  • 7,565
  • 6
  • 55
  • 68