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 <avinesh.kumar@suse.com> 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 20static int fds_limit, first, i; 21static int *fds; 22static char fname[20]; 23 24static 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 47static 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 53static 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 65static struct tst_test test = { 66 .test_all = run, 67 .setup = setup, 68 .cleanup = cleanup, 69 .needs_tmpdir = 1 70}; 71