views:

124

answers:

6

I have an application which can only have 1 instance running at each time, however if a 2nd instance is launched it needs to be logged to a common logfile that the first could also be using.

I have the check for how many instances are running and I was planning on simply logging it to the event logger initially but the application can be running in user or system context and exceptions are thrown when attempting to query the eventlog source as a user so that idea is scrapped as the security logs are inaccessible to the user.

So I wanted to find out what the safest method of have 2 seperate instances of the same application write to a log file would be that would ensure both get an opportunity to write to it.

I would prefer not to use an existing additional framework if avoidable

Any help appreciated.

+2  A: 

A Mutex could be used for interprocess synchronization of a shared resource such as log file. Here's a sample.

Darin Dimitrov
A: 

Much easier way: open the file for exclusive access and catch the exception if it fails:

File.Open(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)

Edit: and if it does fail, wait for the other instance to finish with the file.

Found after 10 seconds of googling, here.

Matt Ball
A: 

You can dodge the problem if you prefer...

If this is a windows app, you can send the first instance a message and then just quit. On receiving the message, the original instance can write to the log file without any issues.

rikh
A: 

Why not use syslog protocol ? This will allow you to deliver the logs in a very standards-based and flexible manner. The protocol itself is quite simple, but there are plenty of examples on the Net, e.g. here. If your app is destined for the enterprise use, having a standard way of logging could be a big plus. (And, you do not need to maintain the files either - it becomes a job of a specialized software that does just that)

Andrew Y
+1  A: 

You could always write to the system event log. No locking or anything needed and the event viewer is more robust than some give it credit for.

In response to your comment, another user asked the question about write permissions for the event log here on SO. The answer linked to the msdn article that describes how to perform that.

See that question here.

SnOrfus
As I posted above I tried this but ran into problems when the application was being run as a user. Is there some way to avoid this? As mentioned the other instance could be running under a system or user account, no guarantee which one would be launched first
Trotts
Updated to link to the a question here on SO that answers your security problem.
SnOrfus
A: 

One way to hack it would be to memory-map the log file. That way, both instances of the application are sharing the same virtual memory image of the file. Then there are a number of ways of implementing a mutex inside the file.

Die in Sente