mplib1/libsrc/lock_file.c
2014-04-22 02:03:26 +01:00

94 lines
2.2 KiB
C

/*
*******************************************************************************
* Copyright (c) 1996 Martin Poole *
*******************************************************************************
**
** WARNING !! WARNING !! WARNING !! WARNING !! WARNING !! WARNING !!
**
** Any changes to be made to this file should first be checked with
** mplib1 source control for library integrity.
**
** mplib1 source control can be reached at mplib1@quatermass.co.uk
**
*
* $Source$
* $Author$
* $Date$
* $Revision$
*
*******************************************************************************
*
* Change History
*
* $Log$
*
*******************************************************************************
*/
#ident "$Header$"
/* ------------------------------------------------------------------
Include files
------------------------------------------------------------------ */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <mplib1/mplib1_config.h>
#include <mplib1/pid_check.h>
#include <mplib1/fprintfile.h>
#include <mplib1/lock_file.h>
/* ------------------------------------------------------------------
defines
------------------------------------------------------------------ */
/* ------------------------------------------------------------------
Code starts here
------------------------------------------------------------------ */
int
lock_reg( int fd, int cmd, short type, off_t offset, short whence, off_t len )
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return( fcntl( fd, cmd, &lock ) );
}
int
lock_file( const char *filename )
{
int fd,val;
int rv = 0;
char buf[PID_STR_LEN];
if ( (fd = open( filename, O_WRONLY | O_CREAT, 0644 )) >= 0)
{
gen_pid_str( buf, getpid() );
if ( (write_lock( fd, 0, SEEK_SET, 0) >= 0)
&& (ftruncate(fd, 0) >= 0)
&& (write(fd,buf,strlen(buf)) == strlen(buf))
&& ( (val = fcntl(fd, F_GETFD, 0)) >= 0)
)
{
val |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, val) >=0 )
rv=1;
}
if (rv==0)
close(fd);
}
return(rv);
}
/* -- End of File -- */