Move file locking code to a separate function.

Failure to lock a file is now fatal.
This commit is contained in:
Daniel Spiljar 2024-09-18 23:48:21 +02:00
parent efc6f92cdb
commit 1a63374e73
Signed by: dspiljar
GPG Key ID: A32CE9C59D8003B5
2 changed files with 35 additions and 32 deletions

View File

@ -1,6 +1,6 @@
/* /*
mboxgrep - scan mailbox for messages matching a regular expression 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 Mboxgrep is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by 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) if (config.lock > LOCK_NONE)
{ mbox_lock (fd, path, 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);
}
errno = 0;
close (fd);
return NULL;
}
}
if (mode[0] == 'r') if (mode[0] == 'r')
{ {
@ -431,3 +402,34 @@ tmpfile_create (void)
} }
return fd; 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);
}
}
}

View File

@ -1,6 +1,6 @@
/* /*
mboxgrep - scan mailbox for messages matching a regular expression 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 Mboxgrep is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by 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); void mbox_close (mbox_t * mbp);
message_t *mbox_read_message (mbox_t * mp); message_t *mbox_read_message (mbox_t * mp);
void mbox_write_message (message_t * m, mbox_t * mbox); void mbox_write_message (message_t * m, mbox_t * mbox);
void mbox_lock (int fd, const char *path, const char *mode);
#endif /* MBOX_H */ #endif /* MBOX_H */