~ruther/CTU-FEE-B0B35APO-Semestral-project

ref: 247d0c106cc3c32caef42a555948bb0b8cd32ff6 CTU-FEE-B0B35APO-Semestral-project/lib-pheripherals/src/serialize_lock.c -rw-r--r-- 1.2 KiB
247d0c10 — František Boháček fix: floating point exception 3 years ago
                                                                                
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
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#include "serialize_lock.h"

const char *serialize_lock_fname = "/run/lock/serialize_lock";
int serialize_lock_fd = -1;

int serialize_lock(int no_wait)
{
  int fd;

  fd = open(serialize_lock_fname,
    O_RDWR      |   /* open the file for both read and write access */
    O_CREAT     |   /* create file if it does not already exist */
    O_CLOEXEC   ,   /* close on execute */
    S_IRUSR     |   /* user permission: read */
    S_IWUSR     );  /* user permission: write */

  if (fd == -1)
    return -1;

  if (no_wait) {
    /* try to lock the "semaphore", if busy report that */
    if (lockf( fd, F_TLOCK, 0 ) == -1) {
      close(fd);
      return errno == EAGAIN? 0: -1;
    }
  } else  {
    /* lock the "semaphore", wait until available */
    if (lockf( fd, F_LOCK, 0 ) == -1)
      return -1;
  }

  serialize_lock_fd = fd;

  return 1;
}

void serialize_unlock(void)
{
  int fd = serialize_lock_fd;

  if (fd == -1)
    return;

  /* close() automatically releases the file lock */
  /* so technically the call with F_ULOCK is not necessary */
  lockf( fd, F_ULOCK, 0 );
  close( fd );
  serialize_lock_fd = -1;
}
Do not follow this link