xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/fork/fork01.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2000 Silicon Graphics, Inc.  All Rights Reserved.
4  * Author: Kathy Olmsted
5  * Co-Pilot: Steve Shaw
6  */
7 
8 /*\
9  *[Description]
10  *
11  * - fork returns without error
12  * - fork returns the pid of the child
13  */
14 
15 #include <errno.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include "tst_test.h"
21 
22 #define	KIDEXIT	42
23 #define FILENAME "childpid"
24 
25 static int fd = -1;
26 
verify_fork(void)27 static void verify_fork(void)
28 {
29 	int kid_status, term_pid, child_pid, pid, ret;
30 
31 	pid = SAFE_FORK();
32 	if (!pid) {
33 		SAFE_FILE_PRINTF(FILENAME, "%d", getpid());
34 		exit(KIDEXIT);
35 	}
36 
37 	term_pid = SAFE_WAITPID(pid, &kid_status, 0);
38 	if (term_pid == pid) {
39 		if (!WIFEXITED(kid_status)) {
40 			tst_res(TFAIL, "child exited abnormally");
41 			return;
42 		}
43 		ret = WEXITSTATUS(kid_status);
44 		if (ret != KIDEXIT)
45 			tst_res(TFAIL, "incorrect child status returned %d", ret);
46 		else
47 			tst_res(TPASS, "correct child status returned %d", ret);
48 
49 		SAFE_FILE_SCANF(FILENAME, "%d", &child_pid);
50 		TST_EXP_EQ_LI(child_pid, pid);
51 	} else {
52 		tst_res(TFAIL, "waitpid() returns %d instead of expected pid %d",
53 				term_pid, pid);
54 	}
55 
56 	tst_reap_children();
57 }
58 
setup(void)59 static void setup(void)
60 {
61 	fd = SAFE_CREAT(FILENAME, 0700);
62 	SAFE_CLOSE(fd);
63 }
64 
cleanup(void)65 static void cleanup(void)
66 {
67 	if (fd > -1)
68 		SAFE_CLOSE(fd);
69 }
70 
71 static struct tst_test test = {
72 	.setup = setup,
73 	.cleanup = cleanup,
74 	.needs_tmpdir = 1,
75 	.forks_child = 1,
76 	.test_all = verify_fork,
77 };
78