summaryrefslogtreecommitdiff
path: root/libfshelp-tests/race.c
blob: 376ada23457a93259bb2bf12fd2fec458d42739e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Test races in the record locking code.

   Copyright (C) 2001 Free Software Foundation, Inc.

   Written by Neal H Walfield <neal@cs.uml.edu>

   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, 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 the GNU Hurd.  If not, see <http://www.gnu.org/licenses/>.  */

#include <stdio.h>
#include <error.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "fs_U.h"
#include <hurd.h>
#include "io_U.h"

int main (int argc, char **argv)
{
  error_t err;
  struct flock64 lock;
  mach_port_t rendezvous = MACH_PORT_NULL;
  int fd;
  int i;
  mach_msg_type_number_t v;
  int blocked = 0;
  char buf[10] = "";
  char *bufp;

  if (argc != 4)
    error (1, 0, "Usage: %s file start len", argv[0]);

  lock.l_whence = SEEK_SET;
  lock.l_start = atoi (argv[2]);
  lock.l_len = atoi (argv[3]);

  fd = file_name_lookup (argv[1], O_READ | O_WRITE | O_CREAT, 0666);
  if (fd == MACH_PORT_NULL)
    error (1, errno, "file_name_lookup");

  for (i = 0; i < 10000; i ++)
    {
      lock.l_type = F_WRLCK;
      err = file_record_lock (fd, F_SETLK64, &lock, rendezvous, MACH_MSG_TYPE_MAKE_SEND);
      if (err)
        {
	  blocked ++;
          err = file_record_lock (fd, F_SETLKW64, &lock, rendezvous, MACH_MSG_TYPE_MAKE_SEND);
	}
      if (err)
        error (1, err, "file_record_lock");

      v = sizeof (buf);
      bufp = buf;
      io_read (fd, &bufp, &v, 0, v);

      v = atoi (bufp);
      sprintf (buf, "%d\n", v + 1);

      v = 10;
      io_write (fd, buf, sizeof (buf), 0, &v);
      if (v == 0)
        error (1, errno, "write (%d)", i);

      lock.l_type = F_UNLCK;
      file_record_lock (fd, F_SETLK64, &lock, rendezvous, MACH_MSG_TYPE_MAKE_SEND);
    }

  mach_port_deallocate (mach_task_self (), fd);

  printf ("Was blocked %d times\n", blocked);
  return 0;
}