• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines Corp., 2001
4  * Ported to LTP: Wayne Boyer
5  */
6 
7 /*
8  * Testcase to check that creat(2) system call returns EMFILE.
9  */
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <sys/types.h>
15 #include <sys/time.h>
16 #include <sys/resource.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <linux/limits.h>
20 #include <unistd.h>
21 #include "tst_test.h"
22 
23 static int *opened_fds, num_opened_fds;
24 
verify_creat(void)25 static void verify_creat(void)
26 {
27 	TEST(creat("filename", 0666));
28 
29 	if (TST_RET != -1) {
30 		tst_res(TFAIL, "call succeeded unexpectedly");
31 		SAFE_CLOSE(TST_RET);
32 		return;
33 	}
34 
35 	if (TST_ERR == EMFILE)
36 		tst_res(TPASS, "creat() failed with EMFILE");
37 	else
38 		tst_res(TFAIL | TTERRNO, "Expected EMFILE");
39 }
40 
setup(void)41 static void setup(void)
42 {
43 	int max_open;
44 	int fd;
45 	char fname[PATH_MAX];
46 
47 	/* get the maximum number of files that we can open */
48 	max_open = getdtablesize();
49 	tst_res(TINFO, "getdtablesize() = %d", max_open);
50 	opened_fds = SAFE_MALLOC(max_open * sizeof(int));
51 
52 	/* now open as many files as we can up to max_open */
53 	do {
54 		snprintf(fname, sizeof(fname), "creat05_%d", num_opened_fds);
55 		fd = SAFE_CREAT(fname, 0666);
56 		opened_fds[num_opened_fds++] = fd;
57 	} while (fd < max_open - 1);
58 
59 	tst_res(TINFO, "Opened additional #%d fds", num_opened_fds);
60 }
61 
cleanup(void)62 static void cleanup(void)
63 {
64 	int i;
65 
66 	for (i = 0; i < num_opened_fds; i++) {
67 		if (close(opened_fds[i])) {
68 			tst_res(TWARN | TERRNO, "close(%i) failed",
69 				opened_fds[i]);
70 		}
71 	}
72 
73 	free(opened_fds);
74 }
75 
76 static struct tst_test test = {
77 	.test_all = verify_creat,
78 	.needs_tmpdir = 1,
79 	.setup = setup,
80 	.cleanup = cleanup,
81 };
82