-
Notifications
You must be signed in to change notification settings - Fork 1
/
io.c
96 lines (81 loc) · 1.48 KB
/
io.c
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
85
86
87
88
89
90
91
92
93
94
95
96
#define _LARGEFILE64_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mem.h"
ssize_t READ(int fd, char *whereto, size_t len)
{
ssize_t cnt=0;
while(len>0)
{
ssize_t rc;
rc = read(fd, whereto, len);
if (rc == -1)
{
if (errno != EINTR)
{
fprintf(stderr, "READ::read: %d\n", errno);
return -1;
}
}
else if (rc == 0)
{
break;
}
else
{
whereto += rc;
len -= rc;
cnt += rc;
}
}
return cnt;
}
char * genlockfilename(char *in)
{
char *dummy = (char *)mymalloc(strlen(in) + strlen(".lock") + 1, "lock filename");
if (!dummy)
{
fprintf(stderr, "genlockfilename::malloc: failure");
return NULL;
}
sprintf(dummy, "%s.lock", in);
return dummy;
}
int lockfile(char *file)
{
char *lfile = genlockfilename(file);
int fd;
if (!lfile)
{
fprintf(stderr, "lockfile::genlockfilename: problem creating lockfile-filename");
return -1;
}
do
{
fd = open(lfile, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd == -1)
{
fprintf(stderr, "lockfile: waiting for file '%s' to become available (delete file %s if this is an error)", file, lfile);
sleep(1);
}
}
while(fd == -1);
free(lfile);
return fd;
}
int unlockfile(char *file, int fd)
{
if (close(fd) == -1)
{
fprintf(stderr, "unlockfile::close: problem closing file: %m");
return -1;
}
return unlink(genlockfilename(file));
}