-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.c
70 lines (64 loc) · 1.52 KB
/
block.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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include "p5.h"
/* only open the file once */
static int fd = -1;
static int devsize = 0;
/* returns the device size (in blocks) if the operation is successful,
* and -1 otherwise */
int dev_open ()
{
struct stat st;
if (fd < 0) {
fd = open ("simulated_device", O_RDWR);
if (fd < 0) {
perror ("open");
return -1;
}
if (fstat (fd, &st) < 0) {
perror ("fstat");
return -1;
}
devsize = st.st_size / BLOCKSIZE;
}
return devsize;
}
/* returns 0 if the operation is successful, and -1 otherwise */
int read_block (int block_num, char * block)
{
if (block_num >= devsize) {
printf ("block number requested %d, maximum %d", block_num, devsize - 1);
return -1;
}
if (lseek (fd, block_num * BLOCKSIZE, SEEK_SET) < 0) {
perror ("lseek");
return -1;
}
if (read (fd, block, BLOCKSIZE) != BLOCKSIZE) {
perror ("read");
return -1;
}
return 0;
}
/* returns 0 if the operation is successful, and -1 otherwise */
int write_block (int block_num, char * block)
{
if (block_num >= devsize) {
printf ("block number requested %d, maximum %d", block_num, devsize - 1);
return -1;
}
if (lseek (fd, block_num * BLOCKSIZE, SEEK_SET) < 0) {
perror ("lseek");
return -1;
}
if (write (fd, block, BLOCKSIZE) != BLOCKSIZE) {
perror ("write");
return -1;
}
if (fsync (fd) < 0)
perror ("fsync"); /* but return success anyway */
return 0;
}