-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdupprac1.c
47 lines (37 loc) · 1009 Bytes
/
dupprac1.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
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
/* This program tests dup(). It duplicates stderr, closes
* stderr, opens a new fd on a text file, prints its new fd
* which should be 2, closes both new file descriptors and
* exits.
* */
int main(int argc, char *argv[]) {
int newfd1 = dup(2);
printf("New fd for stderr: %d\n", newfd1);
if (close(2) == -1) {
perror("close(2)");
exit(EXIT_FAILURE);
}
int newfd2 = open("file.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (newfd2 == -1) {
perror("open newfd2");
close(newfd1);
exit(EXIT_FAILURE);
}
printf("newfd2 = %d\n", newfd2);
if (close(newfd2) == -1) {
perror("close newfd2");
exit(EXIT_FAILURE);
}
if (close(newfd1) == -1) {
perror("close newfd1");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}