Blame manual/examples/ofdlocks.c

Packit 6c4009
/* Open File Description Locks Usage Example
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
#define _GNU_SOURCE
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <sys/types.h>
Packit 6c4009
#include <sys/stat.h>
Packit 6c4009
#include <unistd.h>
Packit 6c4009
#include <fcntl.h>
Packit 6c4009
#include <pthread.h>
Packit 6c4009
Packit 6c4009
#define FILENAME	"/tmp/foo"
Packit 6c4009
#define NUM_THREADS	3
Packit 6c4009
#define ITERATIONS	5
Packit 6c4009
Packit 6c4009
void *
Packit 6c4009
thread_start (void *arg)
Packit 6c4009
{
Packit 6c4009
  int i, fd, len;
Packit 6c4009
  long tid = (long) arg;
Packit 6c4009
  char buf[256];
Packit 6c4009
  struct flock lck = {
Packit 6c4009
    .l_whence = SEEK_SET,
Packit 6c4009
    .l_start = 0,
Packit 6c4009
    .l_len = 1,
Packit 6c4009
  };
Packit 6c4009
Packit 6c4009
  fd = open ("/tmp/foo", O_RDWR | O_CREAT, 0666);
Packit 6c4009
Packit 6c4009
  for (i = 0; i < ITERATIONS; i++)
Packit 6c4009
    {
Packit 6c4009
      lck.l_type = F_WRLCK;
Packit 6c4009
      fcntl (fd, F_OFD_SETLKW, &lck;;
Packit 6c4009
Packit 6c4009
      len = sprintf (buf, "%d: tid=%ld fd=%d\n", i, tid, fd);
Packit 6c4009
Packit 6c4009
      lseek (fd, 0, SEEK_END);
Packit 6c4009
      write (fd, buf, len);
Packit 6c4009
      fsync (fd);
Packit 6c4009
Packit 6c4009
      lck.l_type = F_UNLCK;
Packit 6c4009
      fcntl (fd, F_OFD_SETLK, &lck;;
Packit 6c4009
Packit 6c4009
      /* sleep to ensure lock is yielded to another thread */
Packit 6c4009
      usleep (1);
Packit 6c4009
    }
Packit 6c4009
  pthread_exit (NULL);
Packit 6c4009
}
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main (int argc, char **argv)
Packit 6c4009
{
Packit 6c4009
  long i;
Packit 6c4009
  pthread_t threads[NUM_THREADS];
Packit 6c4009
Packit 6c4009
  truncate (FILENAME, 0);
Packit 6c4009
Packit 6c4009
  for (i = 0; i < NUM_THREADS; i++)
Packit 6c4009
    pthread_create (&threads[i], NULL, thread_start, (void *) i);
Packit 6c4009
Packit 6c4009
  pthread_exit (NULL);
Packit 6c4009
  return 0;
Packit 6c4009
}