xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/waitpid/waitpid03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  * Copyright (c) 2024 SUSE LLC <[email protected]>
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Check that waitpid() returns the exit status of a specific child process
11  * and repeated call on the same process will fail with ECHILD.
12  */
13 
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <signal.h>
17 #include <errno.h>
18 #include <sys/wait.h>
19 
20 #include "tst_test.h"
21 
22 #define	MAX_CHILDREN 25
23 
24 static pid_t children[MAX_CHILDREN];
25 
check_waitpid(pid_t pid,int reaped)26 static void check_waitpid(pid_t pid, int reaped)
27 {
28 	TEST(waitpid(pid, NULL, 0));
29 
30 	if (!reaped && pid == (pid_t)TST_RET) {
31 		tst_res(TPASS, "waitpid(%d) returned correct PID", pid);
32 		return;
33 	}
34 
35 	if (reaped && TST_RET == -1 && TST_ERR == ECHILD) {
36 		tst_res(TPASS | TTERRNO, "waitpid(%d) failed on reaped child",
37 			pid);
38 		return;
39 	}
40 
41 	if (TST_RET == -1) {
42 		tst_res(TFAIL | TTERRNO, "waitpid(%d) failed", pid);
43 		return;
44 	}
45 
46 	if (TST_RET < 0) {
47 		tst_res(TFAIL | TTERRNO,
48 			"Unexpected waitpid(%d) return value %ld", pid,
49 			TST_RET);
50 		return;
51 	}
52 
53 	tst_res(TFAIL, "waitpid(%d) returned unexpected PID %ld", pid, TST_RET);
54 }
55 
run(void)56 static void run(void)
57 {
58 	int i;
59 
60 	for (i = 0; i < MAX_CHILDREN; i++) {
61 		children[i] = SAFE_FORK();
62 
63 		/* Children have nothing to do... */
64 		if (!children[i])
65 			exit(0);
66 	}
67 
68 	/* Wait for one specific child */
69 	i = MAX_CHILDREN / 2;
70 	check_waitpid(children[i], 0);
71 
72 	/* Try the same child again after it was reaped */
73 	check_waitpid(children[i], 1);
74 	tst_reap_children();
75 }
76 
77 static struct tst_test test = {
78 	.test_all = run,
79 	.forks_child = 1
80 };
81