• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2002
4  * Ported from SPIE, section2/iosuite/dup6.c, by Airong Zhang
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Negative test for dup2() with max open file descriptors.
11  */
12 
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include "tst_test.h"
17 #include "tst_safe_macros.h"
18 
19 static int *fildes;
20 static int min;
21 static char pfilname[40];
22 
setup(void)23 static void setup(void)
24 {
25 	min = getdtablesize();	/* get number of files allowed open */
26 	fildes = SAFE_MALLOC((min + 10) * sizeof(int));
27 	memset(fildes, -1, (min + 10) * sizeof(int));
28 	sprintf(pfilname, "./dup205.%d\n", getpid());
29 }
30 
cleanup(void)31 static void cleanup(void)
32 {
33 	if (fildes != NULL)
34 		free(fildes);
35 }
36 
run(void)37 static void run(void)
38 {
39 	int ifile = -1, rc = 0;
40 
41 	fildes[0] = SAFE_CREAT(pfilname, 0666);
42 	fildes[fildes[0]] = fildes[0];
43 	for (ifile = fildes[0] + 1; ifile < min + 10; ifile++) {
44 		TEST(dup2(fildes[ifile - 1], ifile));
45 		fildes[ifile] = TST_RET;
46 		if (fildes[ifile] == -1)
47 			break;
48 		if (fildes[ifile] != ifile)
49 			tst_brk(TFAIL,
50 				"got wrong descriptor number back (%d != %d)",
51 				fildes[ifile], ifile);
52 	}
53 
54 	if (ifile < min) {
55 		tst_res(TFAIL, "Not enough files duped");
56 		rc++;
57 	} else if (ifile > min) {
58 		tst_res(TFAIL, "Too many files duped");
59 		rc++;
60 	}
61 	if (TST_ERR != EBADF && TST_ERR != EMFILE && TST_ERR != EINVAL) {
62 		tst_res(TFAIL, "bad errno on dup2 failure");
63 		rc++;
64 	}
65 
66 	if (rc)
67 		tst_res(TFAIL, "Test failed");
68 	else
69 		tst_res(TPASS, "Test passed");
70 
71 	SAFE_UNLINK(pfilname);
72 	for (ifile = fildes[0]; ifile < min + 10; ifile++) {
73 		if (fildes[ifile] > 0)
74 			SAFE_CLOSE(fildes[ifile]);
75 	}
76 }
77 
78 static struct tst_test test = {
79 	.needs_tmpdir = 1,
80 	.test_all = run,
81 	.setup = setup,
82 	.cleanup = cleanup,
83 };
84