I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.
So how in C# would I so this in the example below?
using System.Diagnostics; ... Process foo = new Process(); foo.StartInfo.FileName = @"C:\bar\foo.exe"; foo.StartInfo.Arguments = "Username Password"; bool isRunning = //TODO: Check to see if process foo.exe is already running if (isRunning) { //TODO: Switch to foo.exe process } else { foo.Start(); }
/proc/<PID> should exists if the process PID is still running.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time. This will display the process for the current shell with four columns: PID returns the unique process ID.
Something like: call system("ps aux &> processes. txt") and the analyse the processes. txt file looking for the process name etc. You may need to write some code like ps aux | grep program_name to see if there exists any instances of program_name running.
A process can spawn another process dynamically using the posix_spawn() or posix_spawnp() function. This spawned process can be either a supervisor or a user process. Example 3-3 creates a new process.
This should do it for ya.
Check Processes
//Namespaces we need to use using System.Diagnostics; public bool IsProcessOpen(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { //now we're going to see if any of the running processes //match the currently running processes. Be sure to not //add the .exe to the name you provide, i.e: NOTEPAD, //not NOTEPAD.EXE or false is always returned even if //notepad is running. //Remember, if you have the process running more than once, //say IE open 4 times the loop thr way it is now will close all 4, //if you want it to just close the first one it finds //then add a return; after the Kill if (clsProcess.ProcessName.Contains(name)) { //if the process is found to be running then we //return a true return true; } } //otherwise we return a false return false; }
You can use LINQ as well,
var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains("<your process name>"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With