• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2000 Silicon Graphics, Inc.  All Rights Reserved.
4  * Copyright (c) 2020 SUSE LLC
5  *
6  */
7 /*\
8  * [Description]
9  * Negative test for dup(2) (too many fds).
10  *
11  * [Algorithm]
12  * Open the maximum allowed number of file descriptors and then try to call
13  * dup() once more and verify it fails with EMFILE.
14  */
15 
16 #include <stdlib.h>
17 #include "tst_test.h"
18 
19 int *fd;
20 int nfds;
21 
run(void)22 static void run(void)
23 {
24 	TEST(dup(fd[0]));
25 
26 	if (TST_RET < -1) {
27 		tst_res(TFAIL, "Invalid dup() return value %ld", TST_RET);
28 		return;
29 	}
30 
31 	if (TST_RET == -1) {
32 		if (TST_ERR == EMFILE)
33 			tst_res(TPASS | TTERRNO, "dup() failed as expected");
34 		else
35 			tst_res(TFAIL | TTERRNO, "dup() failed unexpectedly");
36 		return;
37 	}
38 
39 	tst_res(TFAIL, "dup() succeeded unexpectedly");
40 	SAFE_CLOSE(TST_RET);
41 }
42 
setup(void)43 static void setup(void)
44 {
45 	long maxfds;
46 
47 	maxfds = sysconf(_SC_OPEN_MAX);
48 	if (maxfds == -1)
49 		tst_brk(TBROK, "sysconf(_SC_OPEN_MAX) failed");
50 
51 	fd = SAFE_MALLOC(maxfds * sizeof(int));
52 
53 	fd[0] = SAFE_OPEN("dupfile", O_RDWR | O_CREAT, 0700);
54 
55 	for (nfds = 1; nfds < maxfds; nfds++) {
56 		fd[nfds] = SAFE_DUP(fd[0]);
57 		if (fd[nfds] >= maxfds - 1)
58 			break;
59 	}
60 }
61 
cleanup(void)62 static void cleanup(void)
63 {
64 	int i;
65 
66 	for (i = 0; i < nfds; i++)
67 		SAFE_CLOSE(fd[i]);
68 }
69 
70 static struct tst_test test = {
71 	.test_all = run,
72 	.setup = setup,
73 	.cleanup = cleanup,
74 	.needs_tmpdir = 1,
75 };
76