Run an application if it’s not already running

Today we had a problem about an old Windows XP machine, running a 3rd party executable file. The executable sends info to a light board. Digging into problem I figured out that executable file is stopping with client interaction or by itself from time to time.

What we needed is to check if the app is running constantly. If it has been stopped we should run it. The process is not hanging so we don’t need anything there. Also the machine’s OS is old so we needed something other than WMI or PowerShell. I didn’t waste time to check if those are running on XP or not.

Here is how i solved it;

First I looked up for a batch file to do that and I came up with this thanks to Stack Overflow;

tasklist /FI "IMAGENAME eq TOTALCMD.EXE" /FO CSV &gt; search.log</code>

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

cd "C:\TotalCMD"


del search.log

I tested it with good old TOTALCMD.EXE. You can test this with your executable. It’s pure DOS.

Then I feel like unhappy with the unnecessary log file I created etc. Then I coded a small Console Application and compiled it with .NET 2.0.

Here is the code:

        static void Main(string[] args)
            if (args.Length != 2 || string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]))
                Console.WriteLine(@"Rerun Process

            Process thisProc = Process.GetCurrentProcess();
            if (!IsProcessOpen(args[0].ToLower().Replace(".exe", "")))
                Console.WriteLine("{0} Process Is Already Running", args[0]);

        private static void StartProcess(string[] args)
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = Path.Combine(args[1], args[0]);
            catch (Exception ex)
                Console.WriteLine("Error Rerunning {0}\n{1}", Path.Combine(args[1], args[0]), ex.Message);

        private static bool IsProcessOpen(string name)
            foreach (Process clsProcess in Process.GetProcesses())
                if (clsProcess.ProcessName.ToLower().Contains(name))
                    return true;
            return false;

What this app does is pretty straightforward. It checks for the app name in processes. If not exits, it tries to run it. I used System.Diagnostics.Process to create a new process and redirect output to that process.

Process.GetProcesses() gets all the running processes. Here is the usage if you are not happy with it or want to alter it.

You can call the program like the example below;

RerunApp [Executable] [Path]
RerunApp “MYAPP.EXE” “C:\My Folder\My App\”

You can schedule it with windows task manager with the parameters you want and almost have Windows Service like behavior in old systems when running 3rd party executable files.

Here is the source;

Happy Coding 🙂