1/*
2 *
3 *   Copyright (c) International Business Machines  Corp., 2001
4 *
5 *   This program is free software;  you can redistribute it and/or modify
6 *   it under the terms of the GNU General Public License as published by
7 *   the Free Software Foundation; either version 2 of the License, or
8 *   (at your option) any later version.
9 *
10 *   This program is distributed in the hope that it will be useful,
11 *   but WITHOUT ANY WARRANTY;  without even the implied warranty of
12 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
13 *   the GNU General Public License for more details.
14 *
15 *   You should have received a copy of the GNU General Public License
16 *   along with this program;  if not, write to the Free Software
17 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20/*
21 * NAME
22 *	fcntl12.c
23 *
24 * DESCRIPTION
25 *	Testcase to test that fcntl() sets EMFILE for F_DUPFD command.
26 *
27 * ALGORITHM
28 *	Get the size of the descriptor table of a process, by calling the
29 *	getdtablesize() system call. Then attempt to use the F_DUPFD command
30 *	for fcntl(), which should fail with EMFILE.
31 *
32 * USAGE
33 *	fcntl12
34 *
35 * HISTORY
36 *	07/2001 Ported by Wayne Boyer
37 *
38 * RESTRICTIONS
39 *	NONE
40 */
41
42#include <fcntl.h>
43#include <sys/types.h>
44#include <sys/wait.h>
45#include <errno.h>
46#include "test.h"
47
48char *TCID = "fcntl12";
49int TST_TOTAL = 1;
50
51int fail;
52char fname[20];
53void setup(void);
54void cleanup(void);
55
56int main(int ac, char **av)
57{
58	int lc;
59
60	pid_t pid;
61	int fd, i, status, max_files;
62
63	tst_parse_opts(ac, av, NULL, NULL);
64
65	setup();
66
67	/* check for looping state if -i option is given */
68	for (lc = 0; TEST_LOOPING(lc); lc++) {
69		tst_count = 0;
70
71		tst_resm(TINFO, "Test for errno EMFILE");
72		fail = 0;
73
74		pid = FORK_OR_VFORK();
75		if (pid < 0) {
76			tst_brkm(TBROK | TERRNO, cleanup, "Fork failed");
77		} else if (pid == 0) {
78			max_files = getdtablesize();
79			for (i = 0; i < max_files; i++) {
80				if ((fd = open(fname, O_CREAT | O_RDONLY,
81					       0444)) == -1) {
82					break;
83				}
84			}
85
86			if (fcntl(1, F_DUPFD, 1) != -1) {
87				tst_resm(TFAIL, "fcntl failed to FAIL");
88				exit(1);
89			} else if (errno != EMFILE) {
90				tst_resm(TFAIL, "Expected EMFILE got %d",
91					 errno);
92				exit(1);
93			}
94			exit(0);
95		}
96		waitpid(pid, &status, 0);
97		if (WEXITSTATUS(status) == 0)
98			tst_resm(TPASS, "block 1 PASSED");
99		else
100			tst_resm(TFAIL, "block 1 FAILED");
101	}
102	cleanup();
103	tst_exit();
104}
105
106void setup(void)
107{
108	tst_sig(FORK, DEF_HANDLER, cleanup);
109
110	TEST_PAUSE;
111
112	sprintf(fname, "fcnlt12.%d", getpid());
113	tst_tmpdir();
114}
115
116void cleanup(void)
117{
118	unlink(fname);
119	tst_rmdir();
120}
121