1/*	$OpenBSD: dup2test.c,v 1.3 2003/07/31 21:48:08 deraadt Exp $	*/
2/*
3 *	Written by Artur Grabowski <art@openbsd.org> 2001 Public Domain.
4 */
5#include <stdio.h>
6#include <stdlib.h>
7#include <unistd.h>
8#include <err.h>
9#include <fcntl.h>
10
11int
12main(int argc, char *argv[])
13{
14	int orgfd, fd1, fd2;
15	char temp[] = "/tmp/dup2XXXXXXXXX";
16
17	if ((orgfd = mkstemp(temp)) < 0)
18		err(1, "mkstemp");
19	remove(temp);
20
21	if (ftruncate(orgfd, 1024) != 0)
22		err(1, "ftruncate");
23
24	if ((fd1 = dup(orgfd)) < 0)
25		err(1, "dup");
26
27	/* Set close-on-exec */
28	if (fcntl(fd1, F_SETFD, 1) != 0)
29		err(1, "fcntl(F_SETFD)");
30
31	if ((fd2 = dup2(fd1, fd1 + 1)) < 0)
32		err(1, "dup2");
33
34	/* Test 1: Do we get the right fd? */
35	if (fd2 != fd1 + 1)
36		errx(1, "dup2 didn't give us the right fd");
37
38	/* Test 2: Was close-on-exec cleared? */
39	if (fcntl(fd2, F_GETFD) != 0)
40		errx(1, "dup2 didn't clear close-on-exec");
41
42	return 0;
43}
44