I'm writing a simple peer to peer instant messenger for a local network. It uses an ini file to parse a UUID to use as an identifier across the network. The ini file is accessed through a QSettings object. I have written functionality to enable multiple instances of the program to be run on the same computer. When the first program is run, it reads the ini file for the first entry and if one exists reads it, and replaces it with "INUSE". When closing, it replaces the key value with the original UUID. If another instance of the program reads the ini file and reads an INUSE as the first key value, it creates another after it, takes it, and puts an INUSE tag on the second key value.
This works fine, however, if the program crashes the UUID that was "INUSE" will be lost and INUSE will remain until manually taken out. How can I account for crashing with a system that accomplishes the same thing?
Ive taken a look at QLockFile but can't wrap my head around exactly how I would implement such a system.
Any comments are appreciated.
The current format of the ini file is as follows:
[uuid]
1={uuid1}
2={uuid2}
while program 1 is executing
[uuid]
1=INUSE
2={uuid2}
and after a normal end of program
[uuid]
1={uuid1}
2={uuid2}
Essentially what I need is a way of preserving data between program executions but also signal to other instances that said data is currently being used.
I think the first thing is to identify why is your program crashing. In order to choose the better solution.
QLockFile allows you to prevent multiple process accesing the same file. So this only will be usefull to you if the program is crashing beacuse of that.
What ever is the reason your program is crashing, I would recomend the use of exceptions to perform the correct actions when this occurs:
try {
// Some of your code
} catch (exception &e)
{
// Some error occured, do something about it.
// Like restoring your UUID.
}
You can read more about exception here, and you can always use the QT version Qexception.
Hope it helps
Related
I want to implement a feature, that when my application crashes it saves the current data to a temporary file so it can be recovered on the next launch like many application do (eg. Word or something).
So as far as I could find out this is typically done by just saving the file every few minutes and then loading that last saved file on startup if it exists.
However I was wondering if it could also be done by catching all unhandled exceptions and then call the save method when the application crashes.
The advantage would be that I don't have to write to the disk all the time, cause SSDs don't like that, and the file would really be from the crash time and not 10 minutes old in the worst case.
I've tried this on linux with
signal(SIGSEGV, crashSave);
where crashSave() is the function that calls the save and it seems to work. However I'm not sure if this will work on Windows as well?
And is there a general reason why I should not do this (except that the saved file might be corrupted in few cases) Or what is the advantage of other applications doing timed autosave instead?
I'm writing a Qt/C++ program that does long-running simulations, and to guard against data loss, I wrote some simple autosave behaviour. The program periodically saves to the user's temp directory (using QDir::temp()), and if the program closes gracefully, this file is deleted. If the program starts up and sees the file in that directory, it assumes a previous instance crashed or was forcibly ended, and it prompts the user about loading it.
Now here is the complication - I'd like this functionality to work properly even if multiple instances of the program are used at once. So when the program loads, it can't just look for the presence of an autosave file. If it finds one, it needs to determine if that file was created by a running instance (in which case, there's nothing wrong and nothing to be done) or if it has been left over by a instance that crashed or was forcibly ended (in which case it should prompt the user about loading it).
My program is for Windows/Mac/Linux, so what would be the best way to implement this using Qt or otherwise in a cross-platform fashion?
Edit:
The comments suggested the use of the process identifier, which I can get using QCoreApplication::applicationPid(). I like this idea, but when the program loads and sees a file with a certain PID in the name, how can it look at the other running instances (if any) to see if there is a match?
You can simply use QSaveFile which, as the documentation states:-
The QSaveFile class provides an interface for safely writing to files.
QSaveFile is an I/O device for writing text and binary files, without losing existing data if the writing operation fails.
While writing, the contents will be written to a temporary file, and if no error happened, commit() will move it to the final file. This ensures that no data at the final file is lost in case an error happens while writing, and no partially-written file is ever present at the final location. Always use QSaveFile when saving entire documents to disk.
As for multiple instances, you just need to reflect that in the filename.
Ok so I have a few ideas for checking whether or not an instance of a process is already running but I wanna find out what other people already do/use first. I'm looking to do something like firefox does sometimes where it says firefox is already running blah blah blah, it only checks to see if there is another copy of itself running, I'm not really looking to check to see if there is just an arbitrary named process running just if there is another copy of itself.
I don't know whether or not it would be easier to just set up a system to look for an arbitrary process and just look for itself or if it would be better to implement a system for looking for just that process.
I am trying to eventually to lead into being able to communicate with another process so that I could send messages to it.
So say to do the following just as an example: suppose you have firefox already running then you do a command of firefox URLHERE it opens up the new url in the original window that was opened.
I am also trying to figure out how to implement this so if you have any ideas on the best ways in which to do this then by all means please do let me know as well.
Thanks
Assuming Windows - other operating systems may provide similar constructs but implementation details will vary.
Look into named pipes or named mutexes.
A named mutex solution will be easier to code but it will not give you inter-process communication. The theory goes like this: your process attempts to create a named mutex. If it fails it means that another copy of the process is already running. This is guaranteed by the OS - only one named mutex can be created with a specific name. The trick is then in choosing an appropriate name for your mutex so you don't run the risk of accidental conflict with another program wanting to create/use the same named mutex. For this you could use a GUID. Note however, that a nefarious application could create the named mutex that you're looking for and prevent your application from ever running
The second option is to use a named pipe (same story regarding choosing the name). Your process will attempt to create a pipe with a certain name on startup. If creating the pipe fails because the pipe already exists it will go ahead and attempt to connect to the pipe and then you can have the second process exchange information with the first process (i.e. pass on its arguments so that the original process can perform an action)
I am writing two applications: one to write data to a file and another to read data from a file. These programs will be running at the same time. My fear is that one app might write to the file some data and then the other app tries to read it before it is finished. This may lead to missing data, scrambled data, or crashes.
Not sure what I can do... is there a way to lock the file while in use(set from each app)?
(Note: I will not be using a database.)
I am using VS C++ 6.0... this is one of the companies requirements due to older software.
You should use some kind of synchronization between the two processes. For example create a named event (CreateEvent with a lpName that is not NULL). Initialize the event to
CreateEvent(NULL /*lpEventAttributes*/, FALSE /*bManualReset*/, TRUE /*bInitialState*/, "AnyUniqueNameThatYouChoose"/*lpName*/);
This way when one of the process wants to use the file it should first WaitForSignleObject on the event. When it is done it should SignalEvent thus allowing the other process to access the file.
BTW - VC6 is a really bad compiler. You should consider upgrading to a newer version.
I'm a newbie C++ developer and I'm working on an application which needs to write out a log file every so often, and we've noticed that the log file has been corrupted a few times when running the app. The main scenarios seems to be when the program is shutting down, or crashes, but I'm concerned that this isn't the only time that something may go wrong, as the application was born out of a fairly "quick and dirty" project.
It's not critical to have to the most absolute up-to-date data saved, so one idea that someone mentioned was to alternatively write to two log files, and then if the program crashes at least one will still have proper integrity. But this doesn't smell right to me as I haven't really seen any other application use this method.
Are there any "best practises" or standard "patterns" or frameworks to deal with this problem?
At the moment I'm thinking of doing something like this -
Write data to a temp file
Check the data was written correctly with a hash
Rename the original file, and put the temp file in place.
Delete the original
Then if anything fails I can just roll back by just deleting the temp, and the original be untouched.
You must find the reason why the file gets corrupted. If the app crashes unexpectedly, it can't corrupt the file. The only thing that can happen is that the file is truncated (i.e. the last log messages are missing). But the app can't really jump around in the file and modify something elsewhere (unless you call seek in the logging code which would surprise me).
My guess is that the app is multi threaded and the logging code is being called from several threads which can easily lead to data corrupted before the data is written to the log.
You probably forgot to call fsync() every so often, or the data comes in from different threads without proper synchronization among them. Hard to tell without more information (platform, form of corruption you see).
A workaround would be to use logfile rollover, ie. starting a new file every so often.
I really think that you (and others) are wasting your time when you start adding complexity to log files. The whole point of a log is that it should be simple to use and implement, and should work most of the time. To that end, just write the log to an unbuffered stream (l;ike cerr in a C++ program) and live with any, very occasional in my experience, snafus.
OTOH, if you really need an audit trail of everything your app does, for legal reasons, then you should be using some form of transactional storage such as a SQL database.
Not sure if your app is multi-threaded -- if so, consider using Active Object Pattern (PDF) to put a queue in front of the log and make all writes within a single thread. That thread can commit the log in the background. All logs writes will be asynchronous, and in order, but not necessarily written immediately.
The active object can also batch writes.