xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/exit/exit02.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines Corp., 2001
4  * Ported to LTP: Wayne Boyer
5  * Copyright (c) 2018 Cyril Hrubis <[email protected]>
6  */
7 /*
8  * Fork a process that creates a file and writes a few bytes, and
9  * calls exit WITHOUT calling close(). The parent then reads the
10  * file.  If everything that was written is present in the file, then
11  * the test passes.
12  */
13 
14 #include <stdlib.h>
15 #include "tst_test.h"
16 
17 #define FNAME "test_file"
18 
child_write(void)19 static void child_write(void)
20 {
21 	int fd;
22 
23 	fd = SAFE_CREAT(FNAME, 0666);
24 	SAFE_WRITE(SAFE_WRITE_ALL, fd, FNAME, sizeof(FNAME));
25 	exit(0);
26 }
27 
check_file(void)28 static void check_file(void)
29 {
30 	int fd, len;
31 	char buf[256];
32 
33 	fd = SAFE_OPEN(FNAME, O_RDONLY);
34 	len = SAFE_READ(0, fd, buf, sizeof(buf));
35 
36 	if (len != sizeof(FNAME)) {
37 		tst_res(TFAIL, "Wrong length %i expected %zu", len, sizeof(buf));
38 		goto out;
39 	}
40 
41 	if (memcmp(buf, FNAME, sizeof(FNAME))) {
42 		tst_res(TFAIL, "Wrong data read back");
43 		goto out;
44 	}
45 
46 	tst_res(TPASS, "File written by child read back correctly");
47 out:
48 	SAFE_CLOSE(fd);
49 }
50 
run(void)51 static void run(void)
52 {
53 	int pid;
54 
55 	pid = SAFE_FORK();
56 	if (!pid)
57 		child_write();
58 
59 	tst_reap_children();
60 
61 	check_file();
62 
63 	SAFE_UNLINK(FNAME);
64 }
65 
66 static struct tst_test test = {
67 	.needs_tmpdir = 1,
68 	.forks_child = 1,
69 	.test_all = run,
70 };
71