Wrap waitpid() as a GSource. This is a partial implementation of the "Unix
[platform/upstream/glib.git] / tests / child-test.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #include "config.h"
28
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32
33 #include <glib.h>
34
35 GMainLoop *main_loop;
36 gint alive;
37
38 gint
39 get_a_child (gint ttl)
40 {
41   GPid pid;
42
43   pid = fork ();
44   if (pid < 0)
45     exit (1);
46
47   if (pid > 0)
48     return pid;
49
50   sleep (ttl);
51   _exit (0);
52 }
53
54 gboolean
55 child_watch_callback (GPid pid, gint status, gpointer data)
56 {
57   g_print ("child %d exited, status %d\n", pid, status);
58
59   if (--alive == 0)
60     g_main_loop_quit (main_loop);
61
62   return TRUE;
63 }
64
65 static gpointer
66 test_thread (gpointer data)
67 {
68   GMainLoop *new_main_loop;
69   GSource *source;
70   GPid pid;
71   gint ttl = GPOINTER_TO_INT (data);
72
73   new_main_loop = g_main_loop_new (NULL, FALSE);
74
75   pid = get_a_child (ttl);
76   source = g_child_watch_source_new (pid);
77   g_source_set_callback (source, (GSourceFunc) child_watch_callback, NULL, NULL);
78   g_source_attach (source, g_main_loop_get_context (new_main_loop));
79   g_source_unref (source);
80
81   g_print ("whee! created pid: %d\n", pid);
82   g_main_loop_run (new_main_loop);
83
84 }
85
86 int
87 main (int argc, char *argv[])
88 {
89   g_thread_init (NULL);
90   main_loop = g_main_loop_new (NULL, FALSE);
91
92   system ("/bin/true");
93
94   alive = 2;
95   g_thread_create (test_thread, GINT_TO_POINTER (10), FALSE, NULL);
96   g_thread_create (test_thread, GINT_TO_POINTER (20), FALSE, NULL);
97   
98   g_main_loop_run (main_loop);
99
100   return 0;
101 }