file-dotlock.c revision 860c6cf85bd2a3808ab3a480aa697bac24c291dc
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen/* Copyright (C) 2003 Timo Sirainen */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen/* 0.1 .. 0.2msec */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen#define LOCK_RANDOM_USLEEP_TIME (100000 + (unsigned int)rand() % 100000)
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainenstatic struct dotlock *
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainenfile_dotlock_alloc(const struct dotlock_settings *settings)
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen dotlock->settings.lock_suffix = DEFAULT_LOCK_SUFFIX;
bcf5f1acb2e3891f951fd0848c23b86c35efe7e1Timo Sirainenstatic pid_t read_local_pid(const char *lock_path)
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen /* read line */
8759adc67109b5a12a7af3ed717c7040622a0a04Timo Sirainen /* fix the string */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen /* it should contain pid:host */
6ef7e31619edfaa17ed044b45861d106a86191efTimo Sirainen /* host must be ours */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainenstatic int check_lock(time_t now, struct lock_info *lock_info)
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen time_t stale_timeout = lock_info->set->stale_timeout;
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen i_error("lstat(%s) failed: %m", lock_info->lock_path);
a3dd97fb6d92a89c3de0597fed2d4b044c7aeb84Timo Sirainen if (lock_info->set->immediate_stale_timeout != 0 &&
a3dd97fb6d92a89c3de0597fed2d4b044c7aeb84Timo Sirainen now > st.st_mtime + immediate_stale_timeout &&
a3dd97fb6d92a89c3de0597fed2d4b044c7aeb84Timo Sirainen now > st.st_ctime + immediate_stale_timeout) {
e4d34f2fbee451219599d71505594df704093ce3Timo Sirainen /* old lock file */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen if (unlink(lock_info->lock_path) < 0 && errno != ENOENT) {
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen i_error("unlink(%s) failed: %m", lock_info->lock_path);
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen /* either our first check or someone else got the lock file. */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen /* no pid checking */
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen /* we just checked the pid */
d5cebe7f98e63d4e2822863ef2faa4971e8b3a5dTimo Sirainen /* re-read the pid. even if all times and inodes are the same,
dc9bfb7dc057964238e181d3d8b08751527bb08aTimo Sirainen the PID in the file might have changed if lock files were
if (stale_timeout == 0) {
const char *str;
int fd;
if (write_pid) {
return fd;
const char *str, *p;
if (p != NULL) {
int fd;
if (write_pid) {
const char *lock_path;
unsigned int stale_notify_threshold;
if (do_wait) {
if (ret < 0)
if (ret != 0)
t_push();
unsigned int secs_left =
t_pop();
if (ret > 0) {
if (ret == 0)
return ret;
int old_errno;
const char *lock_path;
return ret;
const char *lock_path;
int ret;
if (ret <= 0) {
const char *lock_path;
int fd;