console - Will this file lock mechanism work or will their be race conditions? -
i have console programm runs different commands. want able run multiple instances of programm in parallel however, want prevent specific commands beeing processed in parallel.
i thought of simple file lock system.
given command "foo" not allowed run in parallel, work?
- before running foo check if file .lock_foo_* exists (if so, abort)
- if not, create file .lock_foo_guid
- check if .lock_foo_guid exists , if no other .lock_foo_* file exists
if there .lock_foo_* file, means instance created 1 @ simultanously , abort , remove our lock file.
i wonder if there race conditions , if that's correct way handle it?
update
i think it's easier expected (at least on windows). think answer thb set me on right track.
i think should work
public bool createlock(string filename){ try{ file.open(string.format(".lock_{0}",filename), filemode.create, fileaccess.readwrite, fileshare.none); } catch (exception exception){ return false; } return true; } the os make sure file created if doesn't exist yet , otherwise raise exception. method should safe. unfortunatly not work on unix though.
your logic looks pretty good. however, if interests you, there exist more 1 command-line utility want, example lockfile , flock.
try man 1 lockfile. suspect that manpage succinctly answer question.
on other hand, if need or prefer implement this, yourself, approach suggest right must sporadically, fail. frustrating, inherent kind of thing trying do. reason brief interval interposes between (1) checking whether process has locked resource , (2) locking resource. happens if, during brief interval, process should lock resource?
what needed atomic operation, somehow checks , locks single, uninterruptible step. fortunately, modern cpus provide such atomic operations , modern operating-system kernels expose them, precisely can indeed reliably want.
if interests you, can consult microsoft's development docs lockfile , lockfileex.
Comments
Post a Comment