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) 2021 Xie Ziyao <xieziyao@huawei.com>
6f08c3bdfSopenharmony_ci */
7f08c3bdfSopenharmony_ci
8f08c3bdfSopenharmony_ci/*\
9f08c3bdfSopenharmony_ci * [Description]
10f08c3bdfSopenharmony_ci *
11f08c3bdfSopenharmony_ci * Check that the parent's file descriptors will not be affected by being
12f08c3bdfSopenharmony_ci * closed in the child.
13f08c3bdfSopenharmony_ci */
14f08c3bdfSopenharmony_ci
15f08c3bdfSopenharmony_ci#include <stdlib.h>
16f08c3bdfSopenharmony_ci
17f08c3bdfSopenharmony_ci#include "tst_test.h"
18f08c3bdfSopenharmony_ci
19f08c3bdfSopenharmony_ci#define TESTFILE "testfile_fork08"
20f08c3bdfSopenharmony_ci
21f08c3bdfSopenharmony_cistatic int fd;
22f08c3bdfSopenharmony_cistatic char buf;
23f08c3bdfSopenharmony_ci
24f08c3bdfSopenharmony_cistatic void run(void)
25f08c3bdfSopenharmony_ci{
26f08c3bdfSopenharmony_ci	int ret;
27f08c3bdfSopenharmony_ci
28f08c3bdfSopenharmony_ci	fd = SAFE_OPEN(TESTFILE, O_RDONLY);
29f08c3bdfSopenharmony_ci	if (!SAFE_FORK()) {
30f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd);
31f08c3bdfSopenharmony_ci		exit(0);
32f08c3bdfSopenharmony_ci	}
33f08c3bdfSopenharmony_ci
34f08c3bdfSopenharmony_ci	if (!SAFE_FORK()) {
35f08c3bdfSopenharmony_ci		SAFE_READ(1, fd, &buf, 1);
36f08c3bdfSopenharmony_ci		if (buf != 'a')
37f08c3bdfSopenharmony_ci			tst_res(TFAIL, "%6d: read '%c' instead of 'a'",
38f08c3bdfSopenharmony_ci				getpid(), buf);
39f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd);
40f08c3bdfSopenharmony_ci		exit(0);
41f08c3bdfSopenharmony_ci	}
42f08c3bdfSopenharmony_ci	tst_reap_children();
43f08c3bdfSopenharmony_ci
44f08c3bdfSopenharmony_ci	ret = read(fd, &buf, 1);
45f08c3bdfSopenharmony_ci	if (ret == 0)
46f08c3bdfSopenharmony_ci		tst_res(TPASS, "read the end of file correctly");
47f08c3bdfSopenharmony_ci	else
48f08c3bdfSopenharmony_ci		tst_res(TFAIL | TERRNO, "read() returns %d, expected 0", ret);
49f08c3bdfSopenharmony_ci
50f08c3bdfSopenharmony_ci	SAFE_CLOSE(fd);
51f08c3bdfSopenharmony_ci}
52f08c3bdfSopenharmony_ci
53f08c3bdfSopenharmony_cistatic void setup(void)
54f08c3bdfSopenharmony_ci{
55f08c3bdfSopenharmony_ci	tst_fill_file(TESTFILE, 'a', 1, 1);
56f08c3bdfSopenharmony_ci}
57f08c3bdfSopenharmony_ci
58f08c3bdfSopenharmony_cistatic void cleanup(void)
59f08c3bdfSopenharmony_ci{
60f08c3bdfSopenharmony_ci	if (fd > 0)
61f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd);
62f08c3bdfSopenharmony_ci}
63f08c3bdfSopenharmony_ci
64f08c3bdfSopenharmony_cistatic struct tst_test test = {
65f08c3bdfSopenharmony_ci	.forks_child = 1,
66f08c3bdfSopenharmony_ci	.needs_tmpdir = 1,
67f08c3bdfSopenharmony_ci	.cleanup = cleanup,
68f08c3bdfSopenharmony_ci	.setup = setup,
69f08c3bdfSopenharmony_ci	.test_all = run,
70f08c3bdfSopenharmony_ci};
71