![]() |
|
Think about Loose Coupling | |
PerlMonks |
comment on |
( #3333=superdoc: print w/replies, xml ) | Need Help?? |
MJD's "flock" talk (File Locking -- Slides) uses these techniques:
...or...
More complete examples of these techniques, slightly modernized: Lock the program name:
Or using the DATA trick:
That second version seems more clever (and mostly in a good way), and simpler, but has one disadvantage. If your use statements are loading a lot of code, or code that has compiletime side effects, it's not a good solution because it cannot be put into a BEGIN block. Putting it into a BEGIN block means the flock on the DATA handle gets parsed, and attempts to run, before Perl has had a chance to scan through the rest of the source code file. That means __DATA__ will not have been seen yet, and thus, you would get "flock() on unopened filehandle DATA at mytest.pl line 8.", or something similar. To understand why, consider what a BEGIN block does; as perl is reading through the source file, it runs each 'use' during compiletime as they're seen. If a BEGIN is seen, that is run in the compiletime phase too. This is done line by line, as the source file is read. Eventually perl reads through the file and finds the __DATA__ line. At that point, the DATA handle is created and opened. But any BEGIN blocks would not have access to that handle, because it just hasn't been seen by perl, and hasn't been activated. The reason we even care about putting the highlander assertion into a BEGIN block is to allow perl to exit before it does unnecessary work. Reading through the source code file is trivial work. But loading other modules could amount to more significant burden, and could also have side effects that take place immediately, which may be undesirable if there is already another copy of this script running. So if the first solution works for your operating system, it's probably preferable for non-trivial scripts. For simple scripts without a lot of startup dependencies, the DATA one is nice for its elegance. Dave In reply to Re: Preventing multiple instances
by davido
|
|