1 /* This testcase is part of GDB, the GNU debugger. 2 3 Copyright 2015-2023 Free Software Foundation, Inc. 4 5 This program is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation; either version 3 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 17 18 #include <unistd.h> 19 #include <stdio.h> 20 #include <sys/types.h> 21 #include <sys/wait.h> 22 #include <errno.h> 23 #include <signal.h> 24 25 int save_parent; 26 27 /* Variable set by GDB. If true, then a fork child (or parent) exits 28 if its parent (or child) exits. Otherwise the process waits 29 forever until either GDB or the alarm kills it. */ 30 volatile int exit_if_relative_exits = 0; 31 32 /* The fork child. Just runs forever. */ 33 34 static int 35 fork_child (void) 36 { 37 /* Don't run forever. */ 38 alarm (180); 39 40 while (1) 41 { 42 if (exit_if_relative_exits) 43 { 44 sleep (1); 45 46 /* Exit if GDB kills the parent. */ 47 if (getppid () != save_parent) 48 break; 49 if (kill (getppid (), 0) != 0) 50 break; 51 } 52 else 53 pause (); 54 } 55 56 return 0; 57 } 58 59 /* The fork parent. Just runs forever. */ 60 61 static int 62 fork_parent (void) 63 { 64 /* Don't run forever. */ 65 alarm (180); 66 67 while (1) 68 { 69 if (exit_if_relative_exits) 70 { 71 int res = wait (NULL); 72 if (res == -1 && errno == EINTR) 73 continue; 74 else if (res == -1) 75 { 76 perror ("wait"); 77 return 1; 78 } 79 else 80 return 0; 81 } 82 else 83 pause (); 84 } 85 86 return 0; 87 } 88 89 int 90 main (void) 91 { 92 pid_t pid; 93 94 save_parent = getpid (); 95 96 /* The parent and child should basically run forever without 97 tripping on any debug event. We want to check that GDB updates 98 the parent and child running states correctly right after the 99 fork. */ 100 pid = fork (); 101 if (pid > 0) 102 return fork_parent (); 103 else if (pid == 0) 104 return fork_child (); 105 else 106 { 107 perror ("fork"); 108 return 1; 109 } 110 } 111