xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/open/open04.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  * Copyright (c) 2022 SUSE LLC Avinesh Kumar <[email protected]>
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Verify that open(2) fails with EMFILE when per-process limit on the number
11  * of open file descriptors has been reached.
12  */
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include "tst_test.h"
17 
18 #define FNAME "open04"
19 
20 static int fds_limit, first, i;
21 static int *fds;
22 static char fname[20];
23 
setup(void)24 static void setup(void)
25 {
26 	int fd;
27 
28 	fds_limit = getdtablesize();
29 	first = SAFE_OPEN(FNAME, O_RDWR | O_CREAT, 0777);
30 
31 	fds = SAFE_MALLOC(sizeof(int) * (fds_limit - first));
32 	fds[0] = first;
33 
34 	for (i = first + 1; i < fds_limit; i++) {
35 		sprintf(fname, FNAME ".%d", i);
36 		fd = open(fname, O_RDWR | O_CREAT, 0777);
37 		if (fd == -1) {
38 			if (errno != EMFILE)
39 				tst_brk(TBROK, "Expected EMFILE but got %d", errno);
40 			fds_limit = i;
41 			break;
42 		}
43 		fds[i - first] = fd;
44 	}
45 }
46 
run(void)47 static void run(void)
48 {
49 	sprintf(fname, FNAME ".%d", fds_limit);
50 	TST_EXP_FAIL2(open(fname, O_RDWR | O_CREAT, 0777), EMFILE);
51 }
52 
cleanup(void)53 static void cleanup(void)
54 {
55 	if (!first || !fds)
56 		return;
57 
58 	for (i = first; i < fds_limit; i++)
59 		SAFE_CLOSE(fds[i - first]);
60 
61 	if (fds)
62 		free(fds);
63 }
64 
65 static struct tst_test test = {
66 	.test_all = run,
67 	.setup = setup,
68 	.cleanup = cleanup,
69 	.needs_tmpdir = 1
70 };
71