//-----------------------------------------------------------------------------
// Copyright © 2003 - Philip Howard - All rights reserved
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//-----------------------------------------------------------------------------
// package	libh/io
// homepage	http://libh.slashusr.org/
//-----------------------------------------------------------------------------
// author	Philip Howard
// email	libh at ipal dot org
// homepage	http://phil.ipal.org/
//-----------------------------------------------------------------------------
// This file is best viewed using a fixed spaced font such as Courier
// and in a display at least 120 columns wide.
//-----------------------------------------------------------------------------

__FMACRO_BEGIN__
//-----------------------------------------------------------------------------
// macro	lock_read
//
// purpose	Simple interface to POSIX fcntl() file/record/range locking.
//		Lock a file/record/range for reading, without waiting.
//
// arguments	1 (int) file descriptor of open file to lock
//		2 (off_t) starting byte offset to begin locking
//		3 (off_t) length of record/range to lock
//
// returns	(int) -1 : error
//		(int)  0 : lock has been obtained
//		(int) >0 : process ID already holding lock
//-----------------------------------------------------------------------------
#define lock_read(f,s,l) ({							\
	struct flock libh__lock;						\
	int _libh_fd_;								\
	libh__lock.l_type = ( F_RDLCK );					\
	libh__lock.l_whence = ( SEEK_SET );					\
	libh__lock.l_start = ( s );						\
	libh__lock.l_len = ( l );						\
	libh__fd = ( f );							\
	fcntl( libh__fd, ( F_SETLK ), & libh__lock ) == 0			\
		? 0								\
		: ({								\
			int libh__errno;					\
			libh__errno = errno;					\
			fcntl( libh__fd, ( F_GETLK ), & libh__lock );		\
			errno = libh__errno;					\
			libh__lock.l_type == ( F_UNLCK )			\
				? -1						\
				: libh__lock.l_pid;				\
		});								\
	})

__FMACRO_END__

