2626typedef struct {
2727 char * log_file ;
2828 bool use_tcp_socket ;
29+ bool create_zombie ;
2930} opts_t ;
3031
32+ static void create_zombie (void )
33+ {
34+ pid_t zombie_pid = fork ();
35+
36+ if (zombie_pid < 0 ) {
37+ perror ("zombie: fork failed" );
38+ return ;
39+ }
40+
41+ if (zombie_pid == 0 ) {
42+ /* This process will become the zombie */
43+
44+ prctl (PR_SET_NAME , "piggie-zombie" );
45+
46+ /* First alive child */
47+ pid_t c1 = fork ();
48+ if (c1 == 0 ) {
49+ prctl (PR_SET_NAME , "stopped-child" );
50+ raise (SIGSTOP ); /* enters stopped task state */
51+ while (1 )
52+ sleep (1 );
53+ }
54+
55+ /* Second alive child */
56+ pid_t c2 = fork ();
57+ if (c2 == 0 ) {
58+ prctl (PR_SET_NAME , "alive-child" );
59+ while (1 )
60+ sleep (1 );
61+ }
62+
63+ /*
64+ * Parent of the two children exits immediately.
65+ * Since *its* parent does not wait(), this
66+ * process becomes a zombie.
67+ */
68+ _exit (0 );
69+ }
70+
71+ /*
72+ * Original parent intentionally does NOT wait()
73+ * zombie_pid stays as a zombie.
74+ */
75+ }
76+
3177void run_tcp_server (void )
3278{
3379 int server_socket , client_socket , ret ;
@@ -192,6 +238,10 @@ static int do_test(void *opts_ptr)
192238 run_tcp_client ();
193239 }
194240
241+ if (opts -> create_zombie ) {
242+ create_zombie ();
243+ }
244+
195245 while (1 ) {
196246 sleep (1 );
197247 printf ("%d\n" , i ++ );
@@ -223,6 +273,12 @@ static int parse_options(int argc, char **argv, bool *usage_error, opts_t *opts)
223273 continue ;
224274 }
225275
276+ if (!strcmp (argv [i ], "--zombie" ) || !strcmp (argv [i ], "-z" )) {
277+ opts -> create_zombie = true;
278+ i ++ ;
279+ continue ;
280+ }
281+
226282 printf ("Unknown option: %s\n" , argv [i ]);
227283 * usage_error = true;
228284 goto out ;
@@ -242,7 +298,7 @@ int main(int argc, char **argv) {
242298
243299 ret = parse_options (argc , argv , & usage_error , & opts );
244300 if (ret ) {
245- fprintf (stderr , "Usage: %s -o/--log-file <log_file> [-t/--tcp-socket]\n" , argv [0 ]);
301+ fprintf (stderr , "Usage: %s -o/--log-file <log_file> [-t/--tcp-socket] [-z|--zombie] \n" , argv [0 ]);
246302 return (usage_error != false);
247303 }
248304
0 commit comments