-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfcntl.cpp
74 lines (63 loc) · 1.75 KB
/
fcntl.cpp
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
#include "faasm/faasm.h"
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define FILE_PATH "/etc/hosts"
int main(int argc, char* argv[])
{
int fd = open(FILE_PATH, O_RDONLY);
if (fd <= 0) {
printf("Unable to open file %s\n", FILE_PATH);
return 1;
}
// Duplicate the fd
int newFd = fcntl(fd, F_DUPFD, 0);
if (newFd <= 0) {
printf("Unable to duplicate fd with fcntl (%i): %i (%s)\n",
newFd,
errno,
strerror(errno));
return 1;
}
if (newFd == fd) {
printf("Expected dup-ed and original fd to be different\n");
return 1;
} else {
printf("dup-ed = %i original = %i\n", newFd, fd);
}
char bufferA[100];
ssize_t readBytesA = read(fd, bufferA, 100);
if (readBytesA <= 0) {
printf("Failed original fd (%li bytes, %i - %s)\n",
readBytesA,
errno,
strerror(errno));
return 1;
}
// Need to reset dup-ed as they point to the same underlying object
lseek(fd, 0, SEEK_SET);
lseek(newFd, 0, SEEK_SET);
char bufferB[100];
ssize_t readBytesB = read(newFd, bufferB, 100);
if (readBytesB <= 0) {
printf("Failed dup-ed fd (%li bytes, %i - %s)\n",
readBytesB,
errno,
strerror(errno));
return 1;
}
// Check output is as expected
if (strcmp(bufferA, bufferB) == 0) {
printf("Contents of %s from dup match\n", FILE_PATH);
} else {
printf("Contents of %s from dup don't match (%s vs %s)\n",
FILE_PATH,
bufferA,
bufferB);
return 1;
}
return 0;
}