xref: /qemu/tests/tcg/multiarch/follow-fork-mode.c (revision 4a1babe5)
1 /*
2  * Test GDB's follow-fork-mode.
3  *
4  * fork() a chain of processes.
5  * Parents sends one byte to their children, and children return their
6  * position in the chain, in order to prove that they survived GDB's fork()
7  * handling.
8  *
9  * SPDX-License-Identifier: GPL-2.0-or-later
10  */
11 #include <assert.h>
12 #include <stdlib.h>
13 #include <sys/wait.h>
14 #include <unistd.h>
15 
16 void break_after_fork(void)
17 {
18 }
19 
20 int main(void)
21 {
22     int depth = 42, err, i, fd[2], status;
23     pid_t child, pid;
24     ssize_t n;
25     char b;
26 
27     for (i = 0; i < depth; i++) {
28         err = pipe(fd);
29         assert(err == 0);
30         child = fork();
31         break_after_fork();
32         assert(child != -1);
33         if (child == 0) {
34             close(fd[1]);
35 
36             n = read(fd[0], &b, 1);
37             close(fd[0]);
38             assert(n == 1);
39             assert(b == (char)i);
40         } else {
41             close(fd[0]);
42 
43             b = (char)i;
44             n = write(fd[1], &b, 1);
45             close(fd[1]);
46             assert(n == 1);
47 
48             pid = waitpid(child, &status, 0);
49             assert(pid == child);
50             assert(WIFEXITED(status));
51             return WEXITSTATUS(status) - 1;
52         }
53     }
54 
55     return depth;
56 }
57