1f08c3bdfSopenharmony_ci// SPDX-License-Identifier: GPL-2.0-or-later
2f08c3bdfSopenharmony_ci/*
3f08c3bdfSopenharmony_ci * Copyright (c) International Business Machines  Corp., 2001
4f08c3bdfSopenharmony_ci * 07/2001 Ported by Wayne Boyer
5f08c3bdfSopenharmony_ci * Copyright (c) Linux Test Project, 2002-2015
6f08c3bdfSopenharmony_ci * Copyright (c) 2023 SUSE LLC Avinesh Kumar <avinesh.kumar@suse.com>
7f08c3bdfSopenharmony_ci */
8f08c3bdfSopenharmony_ci
9f08c3bdfSopenharmony_ci/*\
10f08c3bdfSopenharmony_ci * [Description]
11f08c3bdfSopenharmony_ci *
12f08c3bdfSopenharmony_ci * Verify that, pipe(2) syscall fails with errno EMFILE when
13f08c3bdfSopenharmony_ci * limit on the number of open file descriptors has been reached.
14f08c3bdfSopenharmony_ci */
15f08c3bdfSopenharmony_ci
16f08c3bdfSopenharmony_ci#include "tst_test.h"
17f08c3bdfSopenharmony_ci#include <stdlib.h>
18f08c3bdfSopenharmony_ci
19f08c3bdfSopenharmony_cistatic int fds[2];
20f08c3bdfSopenharmony_cistatic int *opened_fds, num_opened_fds;
21f08c3bdfSopenharmony_ci
22f08c3bdfSopenharmony_cistatic void setup(void)
23f08c3bdfSopenharmony_ci{
24f08c3bdfSopenharmony_ci	int max_fds;
25f08c3bdfSopenharmony_ci
26f08c3bdfSopenharmony_ci	max_fds = getdtablesize();
27f08c3bdfSopenharmony_ci	tst_res(TINFO, "getdtablesize() = %d", max_fds);
28f08c3bdfSopenharmony_ci	opened_fds = SAFE_MALLOC(max_fds * sizeof(int));
29f08c3bdfSopenharmony_ci
30f08c3bdfSopenharmony_ci	do {
31f08c3bdfSopenharmony_ci		SAFE_PIPE(fds);
32f08c3bdfSopenharmony_ci		opened_fds[num_opened_fds++] = fds[0];
33f08c3bdfSopenharmony_ci		opened_fds[num_opened_fds++] = fds[1];
34f08c3bdfSopenharmony_ci	} while (fds[1] < max_fds - 2);
35f08c3bdfSopenharmony_ci
36f08c3bdfSopenharmony_ci	tst_res(TINFO, "Number of fds opened by pipe calls: %d", num_opened_fds);
37f08c3bdfSopenharmony_ci}
38f08c3bdfSopenharmony_ci
39f08c3bdfSopenharmony_cistatic void run(void)
40f08c3bdfSopenharmony_ci{
41f08c3bdfSopenharmony_ci	TST_EXP_FAIL(pipe(fds), EMFILE);
42f08c3bdfSopenharmony_ci}
43f08c3bdfSopenharmony_ci
44f08c3bdfSopenharmony_cistatic void cleanup(void)
45f08c3bdfSopenharmony_ci{
46f08c3bdfSopenharmony_ci	for (int i = 0; i < num_opened_fds; i++)
47f08c3bdfSopenharmony_ci		SAFE_CLOSE(opened_fds[i]);
48f08c3bdfSopenharmony_ci
49f08c3bdfSopenharmony_ci	if (opened_fds)
50f08c3bdfSopenharmony_ci		free(opened_fds);
51f08c3bdfSopenharmony_ci}
52f08c3bdfSopenharmony_ci
53f08c3bdfSopenharmony_cistatic struct tst_test test = {
54f08c3bdfSopenharmony_ci	.setup = setup,
55f08c3bdfSopenharmony_ci	.cleanup = cleanup,
56f08c3bdfSopenharmony_ci	.test_all = run
57f08c3bdfSopenharmony_ci};
58