Question

I have a c program that is logging to a file /var/log/test.log

I have a separate thread that will read the contents of the file and submit them via a http post to my server. This occurs about every hour. My question is will clearing the contents of the file from that thread (eg. fclose(fopen("/var/log/test.log", "w")) cause any errors in the main thread that is actually writing data to the file?

If this does cause an error what is the best alternative? The file should be cleared (but not deleted) every time the data is sent to the server.

I don't think this matters, but I am running OS X 10.9

Was it helpful?

Solution

My question is will clearing the contents of the file from that thread (eg. fclose(fopen("/var/log/test.log", "w")) cause any errors in the main thread that is actually writing data to the file?

Don't think it'll work in general, and depending on the way you write to the file (do you keep it open for writing or close it?) - you may get some nasty race conditions. Even if it does work for you today, you don't know what's going to happen tomorrow or on another OS.

If this does cause an error what is the best alternative? The file should be cleared (but not deleted) every time the data is sent to the server.

It's better to have a single thread writing to a file. You could have your sending thread notify the logging thread that it has sent some data. For example by writing some index to a shared variable or by putting something in a shared synchronized queue. The writing thread will periodically (say every 100 log writes) check what was send and will act accordingly. This is more extensible and will allow you to have multiple threads requesting to do stuff with the log file in a proper manner.

OTHER TIPS

You need to be wary of the inherent race condition. If the reading thread processes data then the writing thread writes more data and then the reading thread truncates the file, you will lose some data. If that is an error, then you have a problem. If you are not synchronizing the threads, this will be a problem which (according to Murphy) will manifest itself only at the worst possible moment. From the perspective of the operating system, however, what you are doing will not cause any errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top