1f08c3bdfSopenharmony_ci// SPDX-License-Identifier: GPL-2.0-only
2f08c3bdfSopenharmony_ci/*
3f08c3bdfSopenharmony_ci * Copyright (c) 2000 Silicon Graphics, Inc.  All Rights Reserved.
4f08c3bdfSopenharmony_ci * Copyright (c) 2020 SUSE LLC
5f08c3bdfSopenharmony_ci *
6f08c3bdfSopenharmony_ci */
7f08c3bdfSopenharmony_ci/*\
8f08c3bdfSopenharmony_ci * [Description]
9f08c3bdfSopenharmony_ci *
10f08c3bdfSopenharmony_ci * Verify that dup(2) syscall fails with errno EMFILE when the per-process
11f08c3bdfSopenharmony_ci * limit on the number of open file descriptors has been reached.
12f08c3bdfSopenharmony_ci */
13f08c3bdfSopenharmony_ci
14f08c3bdfSopenharmony_ci#include <stdlib.h>
15f08c3bdfSopenharmony_ci#include "tst_test.h"
16f08c3bdfSopenharmony_ci
17f08c3bdfSopenharmony_cistatic int *fd;
18f08c3bdfSopenharmony_cistatic int nfds;
19f08c3bdfSopenharmony_ci
20f08c3bdfSopenharmony_cistatic void run(void)
21f08c3bdfSopenharmony_ci{
22f08c3bdfSopenharmony_ci	TST_EXP_FAIL2(dup(fd[0]), EMFILE, "dup(%d)", fd[0]);
23f08c3bdfSopenharmony_ci
24f08c3bdfSopenharmony_ci	if (TST_RET != -1)
25f08c3bdfSopenharmony_ci		SAFE_CLOSE(TST_RET);
26f08c3bdfSopenharmony_ci}
27f08c3bdfSopenharmony_ci
28f08c3bdfSopenharmony_cistatic void setup(void)
29f08c3bdfSopenharmony_ci{
30f08c3bdfSopenharmony_ci	long maxfds;
31f08c3bdfSopenharmony_ci
32f08c3bdfSopenharmony_ci	maxfds = SAFE_SYSCONF(_SC_OPEN_MAX);
33f08c3bdfSopenharmony_ci	fd = SAFE_MALLOC(maxfds * sizeof(int));
34f08c3bdfSopenharmony_ci
35f08c3bdfSopenharmony_ci	fd[0] = SAFE_OPEN("dupfile", O_RDWR | O_CREAT, 0700);
36f08c3bdfSopenharmony_ci
37f08c3bdfSopenharmony_ci	for (nfds = 1; nfds < maxfds; nfds++) {
38f08c3bdfSopenharmony_ci		fd[nfds] = SAFE_DUP(fd[0]);
39f08c3bdfSopenharmony_ci		if (fd[nfds] >= maxfds - 1)
40f08c3bdfSopenharmony_ci			break;
41f08c3bdfSopenharmony_ci	}
42f08c3bdfSopenharmony_ci}
43f08c3bdfSopenharmony_ci
44f08c3bdfSopenharmony_cistatic void cleanup(void)
45f08c3bdfSopenharmony_ci{
46f08c3bdfSopenharmony_ci	int i;
47f08c3bdfSopenharmony_ci
48f08c3bdfSopenharmony_ci	for (i = 0; i < nfds; i++)
49f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd[i]);
50f08c3bdfSopenharmony_ci}
51f08c3bdfSopenharmony_ci
52f08c3bdfSopenharmony_cistatic struct tst_test test = {
53f08c3bdfSopenharmony_ci	.test_all = run,
54f08c3bdfSopenharmony_ci	.setup = setup,
55f08c3bdfSopenharmony_ci	.cleanup = cleanup,
56f08c3bdfSopenharmony_ci	.needs_tmpdir = 1,
57f08c3bdfSopenharmony_ci};
58