xref: /openbsd-src/regress/sys/kern/dup2/dup2test.c (revision 3a3fbb3f2e2521ab7c4a56b7ff7462ebd9095ec5)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <err.h>
5 #include <fcntl.h>
6 
7 int
8 main()
9 {
10 	int orgfd, fd1, fd2;
11 	char temp[] = "/tmp/dup2XXXXXXXXX";
12 
13 	if ((orgfd = mkstemp(temp)) < 0)
14 		err(1, "mkstemp");
15 	remove(temp);
16 
17 	if (ftruncate(orgfd, 1024) != 0)
18 		err(1, "ftruncate");
19 
20 	if ((fd1 = dup(orgfd)) < 0)
21 		err(1, "dup");
22 
23 	/* Set close-on-exec */
24 	if (fcntl(fd1, F_SETFD, 1) != 0)
25 		err(1, "fcntl(F_SETFD)");
26 
27 	if ((fd2 = dup2(fd1, fd1 + 1)) < 0)
28 		err(1, "dup2");
29 
30 	/* Test 1: Do we get the right fd? */
31 	if (fd2 != fd1 + 1)
32 		errx(1, "dup2 didn't give us the right fd");
33 
34 	/* Test 2: Was close-on-exec cleared? */
35 	if (fcntl(fd2, F_GETFD) != 0)
36 		errx(1, "dup2 didn't clear close-on-exec");
37 
38 	return 0;
39 }
40