#include "apr_arch_file_io.h"
#if APR_HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type)
{
int rc;
#if defined(HAVE_FCNTL_H)
{
struct flock l = { 0 };
int fc;
l.l_whence = SEEK_SET;
l.l_start = 0;
l.l_len = 0;
if ((type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED)
l.l_type = F_RDLCK;
else
l.l_type = F_WRLCK;
fc = (type & APR_FLOCK_NONBLOCK) ? F_SETLK : F_SETLKW;
while ((rc = fcntl(thefile->filedes, fc, &l)) < 0 && errno == EINTR)
continue;
if (rc == -1) {
if (errno == EACCES) {
return EAGAIN;
}
return errno;
}
}
#elif defined(HAVE_SYS_FILE_H)
{
int ltype;
if ((type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED)
ltype = LOCK_SH;
else
ltype = LOCK_EX;
if ((type & APR_FLOCK_NONBLOCK) != 0)
ltype |= LOCK_NB;
while ((rc = flock(thefile->filedes, ltype)) < 0 && errno == EINTR)
continue;
if (rc == -1)
return errno;
}
#else
#error No file locking mechanism is available.
#endif
return APR_SUCCESS;
}
APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile)
{
int rc;
#if defined(HAVE_FCNTL_H)
{
struct flock l = { 0 };
l.l_whence = SEEK_SET;
l.l_start = 0;
l.l_len = 0;
l.l_type = F_UNLCK;
while ((rc = fcntl(thefile->filedes, F_SETLKW, &l)) < 0
&& errno == EINTR)
continue;
if (rc == -1)
return errno;
}
#elif defined(HAVE_SYS_FILE_H)
{
while ((rc = flock(thefile->filedes, LOCK_UN)) < 0 && errno == EINTR)
continue;
if (rc == -1)
return errno;
}
#else
#error No file locking mechanism is available.
#endif
return APR_SUCCESS;
}