views:

148

answers:

4

Hello all,

I have an application and I want to be able to check if (for instance) two instances of it used the same arguments on execution. To make it clearer:

myapp 1 2

myapp 1 3

This isn't a Singleton design pattern problem as I can have more than one instance running. I though about checking the running processes, but it seems that I can only get the process name and that doesn't help me.

Writing a file on startup and then having other instances check if that file exists isn't viable due to abnormal program termination which would leave me hanging.

In Linux I solved this by checking /proc/pid/cmdline and parsing the information there.

Does anyone have any idea if I can do something similar on windows?

Cheers

A: 

You can do this via WMI's Win32_Process class.

Reed Copsey
even if the application was started from a batch?
Andre
Yeah. It just looks at what started the process. This is how ProcessExplorer does it, I think.
Reed Copsey
A: 

You want wmic.exe. Try something like:

wmic.exe process list | findstr myapp.exe

Then sort it / parse it / whatever you need to do.

Seth
A: 

wmic is really a great tool to have.

I ended up using this script instead of filling up my code with WMI calls:

wmic process where "name='cmd.exe'" get CommandLine > list.txt

works great!

cheers and thanks you Seth and Reed

Andre
A: 

After some thinking I decided to do things a bit simpler...

Implementing a mutex and checking it's existence is. As I needed to check if the instances started with the same parameters and not if the same application was started, I just needed to decide on the mutex name in runtime!

so...

sprintf(cmdstr,"myapp_%i_%i",arg1,arg2);

DWORD  m_dwLastError;
m_hMutex = CreateMutex(NULL, FALSE, cmdstr); 
m_dwLastError = GetLastError(); 

if(ERROR_ALREADY_EXISTS == m_dwLastError)
{
    found_other = true;
}

and that's it! no parsing, no wmi, no windows development sdk...

Cheers to you all!

Andre
RaymondC warns us quite a bit about this approach - see http://blogs.msdn.com/oldnewthing/archive/2006/06/20/639479.aspx , http://blogs.msdn.com/oldnewthing/archive/2009/02/20/9435239.aspx , and http://blogs.msdn.com/oldnewthing/archive/2007/06/29/3594231.aspx
Paul Betts