xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/fork/fork07.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  * 07/2001 Ported by Wayne Boyer
5  * 07/2002 Limited forking and split "infinite forks" testcase to fork12.c by
6  * Nate Straz
7  * Copyright (c) 2021 Xie Ziyao <[email protected]>
8  */
9 
10 /*\
11  * [Description]
12  *
13  * Check that all children inherit parent's file descriptor.
14  *
15  * Parent opens a file and forks children. Each child reads a byte and checks
16  * that the value is correct. Parent checks that correct number of bytes was
17  * consumed from the file.
18  */
19 
20 #include <stdlib.h>
21 
22 #include "tst_test.h"
23 
24 #define NFORKS 100
25 #define TESTFILE "testfile_fork07"
26 
27 static int fd;
28 static char buf;
29 
run(void)30 static void run(void)
31 {
32 	int ret, i;
33 
34 	fd = SAFE_OPEN(TESTFILE, O_RDONLY);
35 	for (i = 0; i < NFORKS; ++i) {
36 		if (!SAFE_FORK()) {
37 			SAFE_READ(1, fd, &buf, 1);
38 			if (buf != 'a')
39 				tst_res(TFAIL, "%6d: read '%c' instead of 'a'",
40 					getpid(), buf);
41 			exit(0);
42 		}
43 	}
44 	tst_reap_children();
45 
46 	ret = read(fd, &buf, 1);
47 	if (ret == 0)
48 		tst_res(TPASS, "read the end of file correctly");
49 	else
50 		tst_res(TFAIL, "read() returns %d, expected 0", ret);
51 
52 	SAFE_CLOSE(fd);
53 }
54 
setup(void)55 static void setup(void)
56 {
57 	tst_fill_file(TESTFILE, 'a', NFORKS, 1);
58 }
59 
cleanup(void)60 static void cleanup(void)
61 {
62 	if (fd > 0)
63 		SAFE_CLOSE(fd);
64 }
65 
66 static struct tst_test test = {
67 	.forks_child = 1,
68 	.needs_tmpdir = 1,
69 	.cleanup = cleanup,
70 	.setup = setup,
71 	.test_all = run,
72 };
73