From 1a63374e73dc7b8a97c17529974c9f0352edfd8d Mon Sep 17 00:00:00 2001 From: Daniel Spiljar Date: Wed, 18 Sep 2024 23:48:21 +0200 Subject: [PATCH] Move file locking code to a separate function. Failure to lock a file is now fatal. --- src/mbox.c | 64 ++++++++++++++++++++++++++++-------------------------- src/mbox.h | 3 ++- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/src/mbox.c b/src/mbox.c index 9151c05..21571f4 100644 --- a/src/mbox.c +++ b/src/mbox.c @@ -1,6 +1,6 @@ /* mboxgrep - scan mailbox for messages matching a regular expression - Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006, 2023 Daniel Spiljar + Copyright (C) 2000 - 2004, 2006, 2023 - 2024 Daniel Spiljar Mboxgrep is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -90,36 +90,7 @@ mbox_open (const char *path, const char *mode) } if (config.lock > LOCK_NONE) - { -#ifdef HAVE_FLOCK - int op; - - if (mode[0] == 'r') - op = LOCK_SH; - else - op = LOCK_EX; - if (-1 == flock (fd, op)) -#else - memset (&lck, 0, sizeof (struct flock)); - lck.l_whence = SEEK_SET; - if (mode[0] == 'r') - lck.l_type = F_RDLCK; - else - lck.l_type = F_WRLCK; - - if (-1 == fcntl (fd, F_SETLK, &lck)) -#endif /* HAVE_FLOCK */ - { - if (config.merr) - { - fprintf (stderr, "%s: %s: ", APPNAME, path); - perror (NULL); - } - errno = 0; - close (fd); - return NULL; - } - } + mbox_lock (fd, path, mode); if (mode[0] == 'r') { @@ -431,3 +402,34 @@ tmpfile_create (void) } return fd; } + +void +mbox_lock (int fd, const char *path, const char *mode) +{ +#ifdef HAVE_FLOCK + int op; + + if (mode[0] == 'r') + op = LOCK_SH; + else + op = LOCK_EX; + if (-1 == flock (fd, op)) +#else + memset (&lck, 0, sizeof (struct flock)); + lck.l_whence = SEEK_SET; + if (mode[0] == 'r') + lck.l_type = F_RDLCK; + else + lck.l_type = F_WRLCK; + + if (-1 == fcntl (fd, F_SETLK, &lck)) +#endif /* HAVE_FLOCK */ + { + if (config.merr) + { + fprintf (stderr, "%s: %s: ", APPNAME, path); + perror (NULL); + exit (2); + } + } +} diff --git a/src/mbox.h b/src/mbox.h index 098b40a..e739180 100644 --- a/src/mbox.h +++ b/src/mbox.h @@ -1,6 +1,6 @@ /* mboxgrep - scan mailbox for messages matching a regular expression - Copyright (C) 2000 - 2004, 2023 Daniel Spiljar + Copyright (C) 2000 - 2004, 2023 - 2024 Daniel Spiljar Mboxgrep is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -40,5 +40,6 @@ int tmpfile_create (void); void mbox_close (mbox_t * mbp); message_t *mbox_read_message (mbox_t * mp); void mbox_write_message (message_t * m, mbox_t * mbox); +void mbox_lock (int fd, const char *path, const char *mode); #endif /* MBOX_H */