]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libopensrf/osrf_prefork.c
d2537e39b669bc3e0ad2f30563fedef2a439e107
[OpenSRF.git] / src / libopensrf / osrf_prefork.c
1 /**
2         @file osrf_prefork.c
3         @brief Spawn and manage a collection of child process to service requests.
4
5         Spawn a collection of child processes, replacing them as needed.  Forward requests to them
6         and let the children do the work.
7
8         Each child processes some maximum number of requests before it terminates itself.  When a
9         child dies, either deliberately or otherwise, we can spawn another one to replace it,
10         keeping the number of children within a predefined range.
11
12         Use a doubly-linked circular list to keep track of the children to whom we have forwarded
13         a request, and who are still working on them.  Use a separate linear linked list to keep
14         track of children that are currently idle.  Move them back and forth as needed.
15
16         For each child, set up two pipes:
17         - One for the parent to send requests to the child.
18         - One for the child to notify the parent that it is available for another request.
19
20         The message sent to the child represents an XML stanza as received from Jabber.
21
22         When the child finishes processing the request, it writes the string "available" back
23         to the parent.  Then the parent knows that it can send that child another request.
24 */
25
26 #include <errno.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/select.h>
35 #include <sys/wait.h>
36
37 #include "opensrf/utils.h"
38 #include "opensrf/log.h"
39 #include "opensrf/transport_client.h"
40 #include "opensrf/osrf_stack.h"
41 #include "opensrf/osrf_settings.h"
42 #include "opensrf/osrf_application.h"
43
44 #define READ_BUFSIZE 1024
45 #define ABS_MAX_CHILDREN 256
46
47 typedef struct {
48         int max_requests;     /**< How many requests a child processes before terminating. */
49         int min_children;     /**< Minimum number of children to maintain. */
50         int max_children;     /**< Maximum number of children to maintain. */
51         int fd;               /**< Unused. */
52         int data_to_child;    /**< Unused. */
53         int data_to_parent;   /**< Unused. */
54         int current_num_children;   /**< How many children are currently on the list. */
55         int keepalive;        /**< Keepalive time for stateful sessions. */
56         char* appname;        /**< Name of the application. */
57         /** Points to a circular linked list of children. */
58         struct prefork_child_struct* first_child;
59         /** List of of child processes that aren't doing anything at the moment and are
60                 therefore available to service a new request. */
61         struct prefork_child_struct* idle_list;
62         /** List of allocated but unused prefork_children, available for reuse.  Each one is just
63                 raw memory, apart from the "next" pointer used to stitch them together.  In particular,
64                 there is no child process for them, and the file descriptors are not open. */
65         struct prefork_child_struct* free_list;
66         transport_client* connection;  /**< Connection to Jabber. */
67 } prefork_simple;
68
69 struct prefork_child_struct {
70         pid_t pid;            /**< Process ID of the child. */
71         int read_data_fd;     /**< Child uses to read request. */
72         int write_data_fd;    /**< Parent uses to write request. */
73         int read_status_fd;   /**< Parent reads to see if child is available. */
74         int write_status_fd;  /**< Child uses to notify parent when it's available again. */
75         int max_requests;     /**< How many requests a child can process before terminating. */
76         const char* appname;  /**< Name of the application. */
77         int keepalive;        /**< Keepalive time for stateful sessions. */
78         struct prefork_child_struct* next;  /**< Linkage pointer for linked list. */
79         struct prefork_child_struct* prev;  /**< Linkage pointer for linked list. */
80 };
81
82 typedef struct prefork_child_struct prefork_child;
83
84 /** Boolean.  Set to true by a signal handler when it traps SIGCHLD. */
85 static volatile sig_atomic_t child_dead;
86
87 static int prefork_simple_init( prefork_simple* prefork, transport_client* client,
88         int max_requests, int min_children, int max_children );
89 static prefork_child* launch_child( prefork_simple* forker );
90 static void prefork_launch_children( prefork_simple* forker );
91 static void prefork_run( prefork_simple* forker );
92 static void add_prefork_child( prefork_simple* forker, prefork_child* child );
93
94 static void del_prefork_child( prefork_simple* forker, pid_t pid );
95 static int check_children( prefork_simple* forker, int forever );
96 static int  prefork_child_process_request( prefork_child*, char* data );
97 static int prefork_child_init_hook( prefork_child* );
98 static prefork_child* prefork_child_init( prefork_simple* forker,
99         int read_data_fd, int write_data_fd,
100         int read_status_fd, int write_status_fd );
101
102 /* listens on the 'data_to_child' fd and wait for incoming data */
103 static void prefork_child_wait( prefork_child* child );
104 static void prefork_clear( prefork_simple*, bool graceful);
105 static void prefork_child_free( prefork_simple* forker, prefork_child* );
106 static void osrf_prefork_register_routers( const char* appname, bool unregister );
107 static void osrf_prefork_child_exit( prefork_child* );
108
109 static void sigchld_handler( int sig );
110 static void sigusr1_handler( int sig );
111 static void sigusr2_handler( int sig );
112 static void sigterm_handler( int sig );
113 static void sigint_handler( int sig );
114
115 /** Maintain a global pointer to the prefork_simple object
116  *  for the current process so we can refer to it later
117  *  for signal handling.  There will only ever be one
118  *  forker per process.
119  */
120 static prefork_simple *global_forker = NULL;
121
122 /**
123         @brief Spawn and manage a collection of drone processes for servicing requests.
124         @param appname Name of the application.
125         @return 0 if successful, or -1 if error.
126 */
127 int osrf_prefork_run( const char* appname ) {
128
129         if( !appname ) {
130                 osrfLogError( OSRF_LOG_MARK, "osrf_prefork_run requires an appname to run!");
131                 return -1;
132         }
133
134         set_proc_title( "OpenSRF Listener [%s]", appname );
135
136         int maxr = 1000;
137         int maxc = 10;
138         int minc = 3;
139         int kalive = 5;
140
141         // Get configuration settings
142         osrfLogInfo( OSRF_LOG_MARK, "Loading config in osrf_forker for app %s", appname );
143
144         char* max_req      = osrf_settings_host_value( "/apps/%s/unix_config/max_requests", appname );
145         char* min_children = osrf_settings_host_value( "/apps/%s/unix_config/min_children", appname );
146         char* max_children = osrf_settings_host_value( "/apps/%s/unix_config/max_children", appname );
147         char* keepalive    = osrf_settings_host_value( "/apps/%s/keepalive", appname );
148
149         if( !keepalive )
150                 osrfLogWarning( OSRF_LOG_MARK, "Keepalive is not defined, assuming %d", kalive );
151         else
152                 kalive = atoi( keepalive );
153
154         if( !max_req )
155                 osrfLogWarning( OSRF_LOG_MARK, "Max requests not defined, assuming %d", maxr );
156         else
157                 maxr = atoi( max_req );
158
159         if( !min_children )
160                 osrfLogWarning( OSRF_LOG_MARK, "Min children not defined, assuming %d", minc );
161         else
162                 minc = atoi( min_children );
163
164         if( !max_children )
165                 osrfLogWarning( OSRF_LOG_MARK, "Max children not defined, assuming %d", maxc );
166         else
167                 maxc = atoi( max_children );
168
169         free( keepalive );
170         free( max_req );
171         free( min_children );
172         free( max_children );
173         /* --------------------------------------------------- */
174
175         char* resc = va_list_to_string( "%s_listener", appname );
176
177         // Make sure that we haven't already booted
178         if( !osrfSystemBootstrapClientResc( NULL, NULL, resc )) {
179                 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for osrf_prefork_run()" );
180                 free( resc );
181                 return -1;
182         }
183
184         free( resc );
185
186         prefork_simple forker;
187
188         if( prefork_simple_init( &forker, osrfSystemGetTransportClient(), maxr, minc, maxc )) {
189                 osrfLogError( OSRF_LOG_MARK,
190                         "osrf_prefork_run() failed to create prefork_simple object" );
191                 return -1;
192         }
193
194         // Finish initializing the prefork_simple.
195         forker.appname   = strdup( appname );
196         forker.keepalive = kalive;
197         global_forker = &forker;
198
199         // Spawn the children; put them in the idle list.
200         prefork_launch_children( &forker );
201
202         // Tell the router that you're open for business.
203         osrf_prefork_register_routers( appname, false );
204
205         signal( SIGUSR1, sigusr1_handler);
206         signal( SIGUSR2, sigusr2_handler);
207         signal( SIGTERM, sigterm_handler);
208         signal( SIGINT,  sigint_handler );
209         signal( SIGQUIT, sigint_handler );
210
211         // Sit back and let the requests roll in
212         osrfLogInfo( OSRF_LOG_MARK, "Launching osrf_forker for app %s", appname );
213         prefork_run( &forker );
214
215         osrfLogWarning( OSRF_LOG_MARK, "prefork_run() returned - how??" );
216         prefork_clear( &forker, false );
217         return 0;
218 }
219
220 /**
221         @brief Register the application with a specified router.
222         @param appname Name of the application.
223         @param routerName Name of the router.
224         @param routerDomain Domain of the router.
225
226         Tell the router that you're open for business so that it can route requests to you.
227
228         Called only by the parent process.
229 */
230 static void osrf_prefork_send_router_registration(
231                 const char* appname, const char* routerName, 
232             const char* routerDomain, bool unregister ) {
233
234         // Get a pointer to the global transport_client
235         transport_client* client = osrfSystemGetTransportClient();
236
237         // Construct the Jabber address of the router
238         char* jid = va_list_to_string( "%s@%s/router", routerName, routerDomain );
239
240         // Create the registration message, and send it
241         transport_message* msg;
242     if (unregister) {
243
244             osrfLogInfo( OSRF_LOG_MARK, "%s un-registering with router %s", appname, jid );
245             msg = message_init( "unregistering", NULL, NULL, jid, NULL );
246             message_set_router_info( msg, NULL, NULL, appname, "unregister", 0 );
247
248     } else {
249
250             osrfLogInfo( OSRF_LOG_MARK, "%s registering with router %s", appname, jid );
251             msg = message_init( "registering", NULL, NULL, jid, NULL );
252             message_set_router_info( msg, NULL, NULL, appname, "register", 0 );
253     }
254
255         client_send_message( client, msg );
256
257         // Clean up
258         message_free( msg );
259         free( jid );
260 }
261
262 /**
263         @brief Register with a router, or not, according to some config settings.
264         @param appname Name of the application
265         @param RouterChunk A representation of part of the config file.
266
267         Parse a "complex" router configuration chunk.
268
269         Examine the services listed for a given router (normally in opensrf_core.xml).  If
270         there is an entry for this service, or if there are @em no services listed, then
271         register with this router.  Otherwise don't.
272
273         Called only by the parent process.
274 */
275 static void osrf_prefork_parse_router_chunk( 
276     const char* appname, const jsonObject* routerChunk, bool unregister ) {
277
278         const char* routerName = jsonObjectGetString( jsonObjectGetKeyConst( routerChunk, "name" ));
279         const char* domain = jsonObjectGetString( jsonObjectGetKeyConst( routerChunk, "domain" ));
280         const jsonObject* services = jsonObjectGetKeyConst( routerChunk, "services" );
281         osrfLogDebug( OSRF_LOG_MARK, "found router config with domain %s and name %s",
282                 routerName, domain );
283
284         if( services && services->type == JSON_HASH ) {
285                 osrfLogDebug( OSRF_LOG_MARK, "investigating router information..." );
286                 const jsonObject* service_obj = jsonObjectGetKeyConst( services, "service" );
287                 if( !service_obj )
288                         ;    // do nothing (shouldn't happen)
289                 else if( JSON_ARRAY == service_obj->type ) {
290                         // There are multiple services listed.  Register with this router
291                         // if and only if this service is on the list.
292                         int j;
293                         for( j = 0; j < service_obj->size; j++ ) {
294                                 const char* service = jsonObjectGetString( jsonObjectGetIndex( service_obj, j ));
295                                 if( service && !strcmp( appname, service ))
296                                         osrf_prefork_send_router_registration( appname, routerName, domain, unregister );
297                         }
298                 }
299                 else if( JSON_STRING == service_obj->type ) {
300                         // There's only one service listed.  Register with this router
301                         // if and only if this service is the one listed.
302                         if( !strcmp( appname, jsonObjectGetString( service_obj )) )
303                                 osrf_prefork_send_router_registration( appname, routerName, domain, unregister );
304                 }
305         } else {
306                 // This router is not restricted to any set of services,
307                 // so go ahead and register with it.
308                 osrf_prefork_send_router_registration( appname, routerName, domain, unregister );
309         }
310 }
311
312 /**
313         @brief Register the application with one or more routers, according to the configuration.
314         @param appname Name of the application.
315
316         Called only by the parent process.
317 */
318 static void osrf_prefork_register_routers( const char* appname, bool unregister ) {
319
320         jsonObject* routerInfo = osrfConfigGetValueObject( NULL, "/routers/router" );
321
322         int i;
323         for( i = 0; i < routerInfo->size; i++ ) {
324                 const jsonObject* routerChunk = jsonObjectGetIndex( routerInfo, i );
325
326                 if( routerChunk->type == JSON_STRING ) {
327                         /* this accomodates simple router configs */
328                         char* routerName = osrfConfigGetValue( NULL, "/router_name" );
329                         char* domain = osrfConfigGetValue( NULL, "/routers/router" );
330                         osrfLogDebug( OSRF_LOG_MARK, "found simple router settings with router name %s",
331                                 routerName );
332                         osrf_prefork_send_router_registration( appname, routerName, domain, unregister );
333
334                         free( routerName );
335                         free( domain );
336                 } else {
337                         osrf_prefork_parse_router_chunk( appname, routerChunk, unregister );
338                 }
339         }
340
341         jsonObjectFree( routerInfo );
342 }
343
344 /**
345         @brief Initialize a child process.
346         @param child Pointer to the prefork_child representing the new child process.
347         @return Zero if successful, or -1 if not.
348
349         Called only by child processes.  Actions:
350         - Connect to one or more cache servers
351         - Reconfigure logger, if necessary
352         - Discard parent's Jabber connection and open a new one
353         - Dynamically call an application-specific initialization routine
354         - Change the command line as reported by ps
355 */
356 static int prefork_child_init_hook( prefork_child* child ) {
357
358         if( !child ) return -1;
359         osrfLogDebug( OSRF_LOG_MARK, "Child init hook for child %d", child->pid );
360
361         // Connect to cache server(s).
362         osrfSystemInitCache();
363         char* resc = va_list_to_string( "%s_drone", child->appname );
364
365         // If we're a source-client, tell the logger now that we're a new process.
366         char* isclient = osrfConfigGetValue( NULL, "/client" );
367         if( isclient && !strcasecmp( isclient,"true" ))
368                 osrfLogSetIsClient( 1 );
369         free( isclient );
370
371         // Remove traces of our parent's socket connection so we can have our own.
372         osrfSystemIgnoreTransportClient();
373
374         // Connect to Jabber
375         if( !osrfSystemBootstrapClientResc( NULL, NULL, resc )) {
376                 osrfLogError( OSRF_LOG_MARK, "Unable to bootstrap client for osrf_prefork_run()" );
377                 free( resc );
378                 return -1;
379         }
380
381         free( resc );
382
383         // Dynamically call the application-specific initialization function
384         // from a previously loaded shared library.
385         if( ! osrfAppRunChildInit( child->appname )) {
386                 osrfLogDebug( OSRF_LOG_MARK, "Prefork child_init succeeded\n" );
387         } else {
388                 osrfLogError( OSRF_LOG_MARK, "Prefork child_init failed\n" );
389                 return -1;
390         }
391
392         // Change the command line as reported by ps
393         set_proc_title( "OpenSRF Drone [%s]", child->appname );
394         return 0;
395 }
396
397 /**
398         @brief Respond to a client request forwarded by the parent.
399         @param child Pointer to the state of the child process.
400         @param data Pointer to the raw XMPP message received from the parent.
401         @return 0 on success; non-zero means that the child process should clean itself up
402                 and terminate immediately, presumably due to a fatal error condition.
403
404         Called only by a child process.
405 */
406 static int prefork_child_process_request( prefork_child* child, char* data ) {
407         if( !child ) return 0;
408
409         transport_client* client = osrfSystemGetTransportClient();
410
411         // Make sure that we're still connected to Jabber; reconnect if necessary.
412         if( !client_connected( client )) {
413                 osrfSystemIgnoreTransportClient();
414                 osrfLogWarning( OSRF_LOG_MARK, "Reconnecting child to opensrf after disconnect..." );
415                 if( !osrf_system_bootstrap_client( NULL, NULL )) {
416                         osrfLogError( OSRF_LOG_MARK,
417                                 "Unable to bootstrap client in prefork_child_process_request()" );
418                         sleep( 1 );
419                         osrf_prefork_child_exit( child );
420                 }
421         }
422
423         // Construct the message from the xml.
424         transport_message* msg = new_message_from_xml( data );
425
426         // Respond to the transport message.  This is where method calls are buried.
427         osrfAppSession* session = osrf_stack_transport_handler( msg, child->appname );
428         if( !session )
429                 return 0;
430
431         int rc = session->panic;
432
433         if( rc ) {
434                 osrfLogWarning( OSRF_LOG_MARK,
435                         "Drone for session %s terminating immediately", session->session_id );
436                 osrfAppSessionFree( session );
437                 return rc;
438         }
439
440         if( session->stateless && session->state != OSRF_SESSION_CONNECTED ) {
441                 // We're no longer connected to the client, which presumably means that
442                 // we're done with this request.  Bail out.
443                 osrfAppSessionFree( session );
444                 return rc;
445         }
446
447         // If we get this far, then the client has opened an application connection so that it
448         // can send multiple requests directly to the same server drone, bypassing the router
449         // and the listener.  For example, it may need to do a database transaction, requiring
450         // multiple method calls within the same database session.
451
452         // Hence we go into a loop, responding to successive requests from the same client, until
453         // either the client disconnects or an error occurs.
454
455         osrfLogDebug( OSRF_LOG_MARK, "Entering keepalive loop for session %s", session->session_id );
456         int keepalive = child->keepalive;
457         int retval;
458         int recvd;
459         time_t start;
460         time_t end;
461
462         while( 1 ) {
463
464                 // Respond to any input messages.  This is where the method calls are buried.
465                 osrfLogDebug( OSRF_LOG_MARK,
466                         "osrf_prefork calling queue_wait [%d] in keepalive loop", keepalive );
467                 start   = time( NULL );
468                 retval  = osrf_app_session_queue_wait( session, keepalive, &recvd );
469                 end     = time( NULL );
470
471                 osrfLogDebug( OSRF_LOG_MARK, "Data received == %d", recvd );
472
473                 // Now we check a number of possible reasons to exit the loop.
474
475                 // If the method call decided to terminate immediately,
476                 // note that for future reference.
477                 if( session->panic )
478                         rc = 1;
479
480                 // If an error occurred when we tried to service the request, exit the loop.
481                 if( retval ) {
482                         osrfLogError( OSRF_LOG_MARK, "queue-wait returned non-success %d", retval );
483                         break;
484                 }
485
486                 // If the client disconnected, exit the loop.
487                 if( session->state != OSRF_SESSION_CONNECTED )
488                         break;
489
490                 // If we timed out while waiting for a request, exit the loop.
491                 if( !recvd && (end - start) >= keepalive ) {
492                         osrfLogInfo( OSRF_LOG_MARK,
493                                 "No request was received in %d seconds, exiting stateful session", keepalive );
494                         osrfAppSessionStatus(
495                                 session,
496                                 OSRF_STATUS_TIMEOUT,
497                                 "osrfConnectStatus",
498                                 0, "Disconnected on timeout" );
499
500                         break;
501                 }
502
503                 // If the child process has decided to terminate immediately, exit the loop.
504                 if( rc )
505                         break;
506         }
507
508         osrfLogDebug( OSRF_LOG_MARK, "Exiting keepalive loop for session %s", session->session_id );
509         osrfAppSessionFree( session );
510         return rc;
511 }
512
513 /**
514         @brief Partially initialize a prefork_simple provided by the caller.
515         @param prefork Pointer to a a raw prefork_simple to be initialized.
516         @param client Pointer to a transport_client (connection to Jabber).
517         @param max_requests The maximum number of requests that a child process may service
518                         before terminating.
519         @param min_children Minimum number of child processes to maintain.
520         @param max_children Maximum number of child processes to maintain.
521         @return 0 if successful, or 1 if not (due to invalid parameters).
522 */
523 static int prefork_simple_init( prefork_simple* prefork, transport_client* client,
524                 int max_requests, int min_children, int max_children ) {
525
526         if( min_children > max_children ) {
527                 osrfLogError( OSRF_LOG_MARK,  "min_children (%d) is greater "
528                         "than max_children (%d)", min_children, max_children );
529                 return 1;
530         }
531
532         if( max_children > ABS_MAX_CHILDREN ) {
533                 osrfLogError( OSRF_LOG_MARK,  "max_children (%d) is greater than ABS_MAX_CHILDREN (%d)",
534                         max_children, ABS_MAX_CHILDREN );
535                 return 1;
536         }
537
538         osrfLogInfo( OSRF_LOG_MARK, "Prefork launching child with max_request=%d,"
539                 "min_children=%d, max_children=%d", max_requests, min_children, max_children );
540
541         /* flesh out the struct */
542         prefork->max_requests = max_requests;
543         prefork->min_children = min_children;
544         prefork->max_children = max_children;
545         prefork->fd           = 0;
546         prefork->data_to_child = 0;
547         prefork->data_to_parent = 0;
548         prefork->current_num_children = 0;
549         prefork->keepalive    = 0;
550         prefork->appname      = NULL;
551         prefork->first_child  = NULL;
552         prefork->idle_list    = NULL;
553         prefork->free_list    = NULL;
554         prefork->connection   = client;
555
556         return 0;
557 }
558
559 /**
560         @brief Spawn a new child process and put it in the idle list.
561         @param forker Pointer to the prefork_simple that will own the process.
562         @return Pointer to the new prefork_child, or not at all.
563
564         Spawn a new child process.  Create a prefork_child for it and put it in the idle list.
565
566         After forking, the parent returns a pointer to the new prefork_child.  The child
567         services its quota of requests and then terminates without returning.
568 */
569 static prefork_child* launch_child( prefork_simple* forker ) {
570
571         pid_t pid;
572         int data_fd[2];
573         int status_fd[2];
574
575         // Set up the data and status pipes
576         if( pipe( data_fd ) < 0 ) { /* build the data pipe*/
577                 osrfLogError( OSRF_LOG_MARK,  "Pipe making error" );
578                 return NULL;
579         }
580
581         if( pipe( status_fd ) < 0 ) {/* build the status pipe */
582                 osrfLogError( OSRF_LOG_MARK,  "Pipe making error" );
583                 close( data_fd[1] );
584                 close( data_fd[0] );
585                 return NULL;
586         }
587
588         osrfLogInternal( OSRF_LOG_MARK, "Pipes: %d %d %d %d",
589                 data_fd[0], data_fd[1], status_fd[0], status_fd[1] );
590
591         // Create and initialize a prefork_child for the new process
592         prefork_child* child = prefork_child_init( forker, data_fd[0],
593                 data_fd[1], status_fd[0], status_fd[1] );
594
595         if( (pid=fork()) < 0 ) {
596                 osrfLogError( OSRF_LOG_MARK, "Forking Error" );
597                 prefork_child_free( forker, child );
598                 return NULL;
599         }
600
601         // Add the new child to the head of the idle list
602         child->next = forker->idle_list;
603         forker->idle_list = child;
604
605         if( pid > 0 ) {  /* parent */
606
607                 signal( SIGCHLD, sigchld_handler );
608                 ( forker->current_num_children )++;
609                 child->pid = pid;
610
611                 osrfLogDebug( OSRF_LOG_MARK, "Parent launched %d", pid );
612                 /* *no* child pipe FD's can be closed or the parent will re-use fd's that
613                         the children are currently using */
614                 return child;
615         }
616
617         else { /* child */
618
619                 // we don't want to adopt our parent's handlers.
620                 signal( SIGUSR1, SIG_DFL );
621                 signal( SIGUSR2, SIG_DFL );
622                 signal( SIGTERM, SIG_DFL );
623                 signal( SIGINT,  SIG_DFL );
624                 signal( SIGQUIT, SIG_DFL );
625                 signal( SIGCHLD, SIG_DFL );
626
627                 osrfLogInternal( OSRF_LOG_MARK,
628                         "I am new child with read_data_fd = %d and write_status_fd = %d",
629                         child->read_data_fd, child->write_status_fd );
630
631                 child->pid = getpid();
632                 close( child->write_data_fd );
633                 close( child->read_status_fd );
634
635                 /* do the initing */
636                 if( prefork_child_init_hook( child ) == -1 ) {
637                         osrfLogError( OSRF_LOG_MARK,
638                                 "Forker child going away because we could not connect to OpenSRF..." );
639                         osrf_prefork_child_exit( child );
640                 }
641
642                 prefork_child_wait( child );      // Should exit without returning
643                 osrf_prefork_child_exit( child ); // Just to be sure
644                 return NULL;  // Unreachable, but it keeps the compiler happy
645         }
646 }
647
648 /**
649         @brief Terminate a child process.
650         @param child Pointer to the prefork_child representing the child process (not used).
651
652         Called only by child processes.  Dynamically call an application-specific shutdown
653         function from a previously loaded shared library; then exit.
654 */
655 static void osrf_prefork_child_exit( prefork_child* child ) {
656         osrfAppRunExitCode();
657         exit( 0 );
658 }
659
660 /**
661         @brief Launch all the child processes, putting them in the idle list.
662         @param forker Pointer to the prefork_simple that will own the children.
663
664         Called only by the parent process (in order to become a parent).
665 */
666 static void prefork_launch_children( prefork_simple* forker ) {
667         if( !forker ) return;
668         int c = 0;
669         while( c++ < forker->min_children )
670                 launch_child( forker );
671 }
672
673 /**
674         @brief Signal handler for SIGCHLD: note that a child process has terminated.
675         @param sig The value of the trapped signal; always SIGCHLD.
676
677         Set a boolean to be checked later.
678 */
679 static void sigchld_handler( int sig ) {
680         signal( SIGCHLD, sigchld_handler );
681         child_dead = 1;
682 }
683
684 /**
685         @brief Signal handler for SIGUSR1
686         @param sig The value of the trapped signal; always SIGUSR1.
687
688         Send unregister command to all registered routers.
689 */
690 static void sigusr1_handler( int sig ) {
691         if (!global_forker) return;
692         osrf_prefork_register_routers(global_forker->appname, true);
693         signal( SIGUSR1, sigusr1_handler );
694 }
695
696 /**
697         @brief Signal handler for SIGUSR2
698         @param sig The value of the trapped signal; always SIGUSR2.
699
700         Send register command to all known routers
701 */
702 static void sigusr2_handler( int sig ) {
703         if (!global_forker) return;
704         osrf_prefork_register_routers(global_forker->appname, false);
705         signal( SIGUSR2, sigusr2_handler );
706 }
707
708 /**
709         @brief Signal handler for SIGTERM
710         @param sig The value of the trapped signal; always SIGTERM
711
712         Perform a graceful prefork server shutdown.
713 */
714 static void sigterm_handler(int sig) {
715         if (!global_forker) return;
716         osrfLogInfo(OSRF_LOG_MARK, "server: received SIGTERM, shutting down");
717         prefork_clear(global_forker, true);
718         _exit(0);
719 }
720
721 /**
722         @brief Signal handler for SIGINT or SIGQUIT
723         @param sig The value of the trapped signal
724
725         Perform a non-graceful prefork server shutdown.
726 */
727 static void sigint_handler(int sig) {
728         if (!global_forker) return;
729         osrfLogInfo(OSRF_LOG_MARK, "server: received SIGINT/QUIT, shutting down");
730         prefork_clear(global_forker, false);
731         _exit(0);
732 }
733
734 /**
735         @brief Replenish the collection of child processes, after one has terminated.
736         @param forker Pointer to the prefork_simple that manages the child processes.
737
738         The parent calls this function when it notices (via a signal handler) that
739         a child process has died.
740
741         Wait on the dead children so that they won't be zombies.  Spawn new ones as needed
742         to maintain at least a minimum number.
743 */
744 void reap_children( prefork_simple* forker ) {
745
746         pid_t child_pid;
747
748         // Reset our boolean so that we can detect any further terminations.
749         child_dead = 0;
750
751         // Bury the children so that they won't be zombies.  WNOHANG means that waitpid() returns
752         // immediately if there are no waitable children, instead of waiting for more to die.
753         // Ignore the return code of the child.  We don't do an autopsy.
754         while( (child_pid = waitpid( -1, NULL, WNOHANG )) > 0 ) {
755                 --forker->current_num_children;
756                 del_prefork_child( forker, child_pid );
757         }
758
759         // Spawn more children as needed.
760         while( forker->current_num_children < forker->min_children )
761                 launch_child( forker );
762 }
763
764 /**
765         @brief Read transport_messages and dispatch them to child processes for servicing.
766         @param forker Pointer to the prefork_simple that manages the child processes.
767
768         This is the main loop of the parent process, and once entered, does not exit.
769
770         For each usable transport_message received: look for an idle child to service it.  If
771         no idle children are available, either spawn a new one or, if we've already spawned the
772         maximum number of children, wait for one to become available.  Once a child is available
773         by whatever means, write an XML version of the input message, to a pipe designated for
774         use by that child.
775 */
776 static void prefork_run( prefork_simple* forker ) {
777
778         if( NULL == forker->idle_list )
779                 return;   // No available children, and we haven't even started yet
780
781         transport_message* cur_msg = NULL;
782
783         while( 1 ) {
784
785                 if( forker->first_child == NULL && forker->idle_list == NULL ) {/* no more children */
786                         osrfLogWarning( OSRF_LOG_MARK, "No more children..." );
787                         return;
788                 }
789
790                 // Wait indefinitely for an input message
791                 osrfLogDebug( OSRF_LOG_MARK, "Forker going into wait for data..." );
792                 cur_msg = client_recv( forker->connection, -1 );
793
794                 if( cur_msg == NULL )
795                         continue;           // Error?  Interrupted by a signal?  Try again...
796
797                 message_prepare_xml( cur_msg );
798                 const char* msg_data = cur_msg->msg_xml;
799                 if( ! msg_data || ! *msg_data ) {
800                         osrfLogWarning( OSRF_LOG_MARK, "Received % message from %s, thread %",
801                                 (msg_data ? "empty" : "NULL"), cur_msg->sender, cur_msg->thread );
802                         message_free( cur_msg );
803                         continue;       // Message not usable; go on to the next one.
804                 }
805
806                 int honored = 0;     /* will be set to true when we service the request */
807                 int no_recheck = 0;
808
809                 while( ! honored ) {
810
811             if( !no_recheck ) {
812                 if(check_children( forker, 0 ) < 0) {
813                     continue; // check failed, try again
814                 }
815             }
816             no_recheck = 0;
817
818                         osrfLogDebug( OSRF_LOG_MARK, "Server received inbound data" );
819
820                         prefork_child* cur_child = NULL;
821
822                         // Look for an available child in the idle list.  Since the idle list operates
823                         // as a stack, the child we get is the one that was most recently active, or
824                         // most recently spawned.  That means it's the one most likely still to be in
825                         // physical memory, and the one least likely to have to be swapped in.
826                         while( forker->idle_list ) {
827
828                                 osrfLogDebug( OSRF_LOG_MARK, "Looking for idle child" );
829                                 // Grab the prefork_child at the head of the idle list
830                                 cur_child = forker->idle_list;
831                                 forker->idle_list = cur_child->next;
832                                 cur_child->next = NULL;
833
834                                 osrfLogInternal( OSRF_LOG_MARK,
835                                         "Searching for available child. cur_child->pid = %d", cur_child->pid );
836                                 osrfLogInternal( OSRF_LOG_MARK, "Current num children %d",
837                                         forker->current_num_children );
838
839                                 osrfLogDebug( OSRF_LOG_MARK, "forker sending data to %d", cur_child->pid );
840                                 osrfLogInternal( OSRF_LOG_MARK, "Writing to child fd %d",
841                                         cur_child->write_data_fd );
842
843                                 int written = write( cur_child->write_data_fd, msg_data, strlen( msg_data ) + 1 );
844                                 if( written < 0 ) {
845                                         // This child appears to be dead or unusable.  Discard it.
846                                         osrfLogWarning( OSRF_LOG_MARK, "Write returned error %d: %s",
847                                                 errno, strerror( errno ));
848                                         kill( cur_child->pid, SIGKILL );
849                                         del_prefork_child( forker, cur_child->pid );
850                                         continue;
851                                 }
852
853                                 add_prefork_child( forker, cur_child );  // Add it to active list
854                                 honored = 1;
855                                 break;
856                         }
857
858                         /* if none available, add a new child if we can */
859                         if( ! honored ) {
860                                 osrfLogDebug( OSRF_LOG_MARK, "Not enough children, attempting to add..." );
861
862                                 if( forker->current_num_children < forker->max_children ) {
863                                         osrfLogDebug( OSRF_LOG_MARK,  "Launching new child with current_num = %d",
864                                                 forker->current_num_children );
865
866                                         launch_child( forker );  // Put a new child into the idle list
867                                         if( forker->idle_list ) {
868
869                                                 // Take the new child from the idle list
870                                                 prefork_child* new_child = forker->idle_list;
871                                                 forker->idle_list = new_child->next;
872                                                 new_child->next = NULL;
873
874                                                 osrfLogDebug( OSRF_LOG_MARK, "Writing to new child fd %d : pid %d",
875                                                         new_child->write_data_fd, new_child->pid );
876
877                                                 int written = write(
878                                                         new_child->write_data_fd, msg_data, strlen( msg_data ) + 1 );
879                                                 if( written < 0 ) {
880                                                         // This child appears to be dead or unusable.  Discard it.
881                                                         osrfLogWarning( OSRF_LOG_MARK, "Write returned error %d: %s",
882                                                                 errno, strerror( errno ));
883                                                         kill( cur_child->pid, SIGKILL );
884                                                         del_prefork_child( forker, cur_child->pid );
885                                                 } else {
886                                                         add_prefork_child( forker, new_child );
887                                                         honored = 1;
888                                                 }
889                                         }
890                 } else {
891                     osrfLogWarning( OSRF_LOG_MARK, "Could not launch a new child as %d children "
892                         "were already running; consider increasing max_children for this "
893                         "application higher than %d in the OpenSRF configuration if this "
894                         "message occurs frequently",
895                         forker->current_num_children, forker->max_children );
896                 }
897             }
898
899                         if( !honored ) {
900                                 osrfLogWarning( OSRF_LOG_MARK, "No children available, waiting..." );
901                                 if( check_children( forker, 1 ) >= 0 ) {
902                                     // Tell the loop not to call check_children again, since we just successfully called it
903                                     no_recheck = 1;
904                 }
905                         }
906
907                         if( child_dead )
908                                 reap_children( forker );
909
910                 } // end while( ! honored )
911
912                 message_free( cur_msg );
913
914         } /* end top level listen loop */
915 }
916
917
918 /**
919         @brief See if any children have become available.
920         @param forker Pointer to the prefork_simple that owns the children.
921         @param forever Boolean: true if we should wait indefinitely.
922     @return 0 or greater if successful, -1 on select error/interrupt
923
924         Call select() for all the children in the active list.  Read each active file
925         descriptor and move the corresponding child to the idle list.
926
927         If @a forever is true, wait indefinitely for input.  Otherwise return immediately if
928         there are no active file descriptors.
929 */
930 static int check_children( prefork_simple* forker, int forever ) {
931
932         if( child_dead )
933                 reap_children( forker );
934
935         if( NULL == forker->first_child ) {
936                 // If forever is true, then we're here because we've run out of idle
937                 // processes, so there should be some active ones around, except during
938                 // graceful shutdown, as we wait for all active children to become idle.
939                 // If forever is false, then the children may all be idle, and that's okay.
940                 if( forever )
941                         osrfLogDebug( OSRF_LOG_MARK, "No active child processes to check" );
942                 return 0;
943         }
944
945         int select_ret;
946         fd_set read_set;
947         FD_ZERO( &read_set );
948         int max_fd = 0;
949         int n;
950
951         // Prepare to select() on pipes from all the active children
952         prefork_child* cur_child = forker->first_child;
953         do {
954                 if( cur_child->read_status_fd > max_fd )
955                         max_fd = cur_child->read_status_fd;
956                 FD_SET( cur_child->read_status_fd, &read_set );
957                 cur_child = cur_child->next;
958         } while( cur_child != forker->first_child );
959
960         FD_CLR( 0, &read_set ); /* just to be sure */
961
962         if( forever ) {
963
964                 if( (select_ret=select( max_fd + 1, &read_set, NULL, NULL, NULL )) == -1 ) {
965                         osrfLogWarning( OSRF_LOG_MARK, "Select returned error %d on check_children: %s",
966                                 errno, strerror( errno ));
967                 }
968                 osrfLogInfo( OSRF_LOG_MARK,
969                         "select() completed after waiting on children to become available" );
970
971         } else {
972
973                 struct timeval tv;
974                 tv.tv_sec   = 0;
975                 tv.tv_usec  = 0;
976
977                 if( (select_ret=select( max_fd + 1, &read_set, NULL, NULL, &tv )) == -1 ) {
978                         osrfLogWarning( OSRF_LOG_MARK, "Select returned error %d on check_children: %s",
979                                 errno, strerror( errno ));
980                 }
981         }
982
983     if( select_ret <= 0 ) // we're done here
984         return select_ret;
985
986         // Check each child in the active list.
987         // If it has responded, move it to the idle list.
988         cur_child = forker->first_child;
989         prefork_child* next_child = NULL;
990         int num_handled = 0;
991         do {
992                 next_child = cur_child->next;
993                 if( FD_ISSET( cur_child->read_status_fd, &read_set )) {
994                         osrfLogDebug( OSRF_LOG_MARK,
995                                 "Server received status from a child %d", cur_child->pid );
996
997                         num_handled++;
998
999                         /* now suck off the data */
1000                         char buf[64];
1001                         if( (n=read( cur_child->read_status_fd, buf, sizeof( buf ) - 1 )) < 0 ) {
1002                                 osrfLogWarning( OSRF_LOG_MARK,
1003                                         "Read error after select in child status read with errno %d: %s",
1004                                         errno, strerror( errno ));
1005                         }
1006                         else {
1007                                 buf[n] = '\0';
1008                                 osrfLogDebug( OSRF_LOG_MARK,  "Read %d bytes from status buffer: %s", n, buf );
1009                         }
1010
1011                         // Remove the child from the active list
1012                         if( forker->first_child == cur_child ) {
1013                                 if( cur_child->next == cur_child )
1014                                         forker->first_child = NULL;   // only child in the active list
1015                                 else
1016                                         forker->first_child = cur_child->next;
1017                         }
1018                         cur_child->next->prev = cur_child->prev;
1019                         cur_child->prev->next = cur_child->next;
1020
1021                         // Add it to the idle list
1022                         cur_child->prev = NULL;
1023                         cur_child->next = forker->idle_list;
1024                         forker->idle_list = cur_child;
1025                 }
1026                 cur_child = next_child;
1027         } while( forker->first_child && forker->first_child != next_child );
1028
1029     return select_ret;
1030 }
1031
1032 /**
1033         @brief Service up a set maximum number of requests; then shut down.
1034         @param child Pointer to the prefork_child representing the child process.
1035
1036         Called only by child process.
1037
1038         Enter a loop, for up to max_requests iterations.  On each iteration:
1039         - Wait indefinitely for a request from the parent.
1040         - Service the request.
1041         - Increment a counter.  If the limit hasn't been reached, notify the parent that you
1042         are available for another request.
1043
1044         After exiting the loop, shut down and terminate the process.
1045 */
1046 static void prefork_child_wait( prefork_child* child ) {
1047
1048         int i,n;
1049         growing_buffer* gbuf = buffer_init( READ_BUFSIZE );
1050         char buf[READ_BUFSIZE];
1051
1052         for( i = 0; i < child->max_requests; i++ ) {
1053
1054                 n = -1;
1055                 int gotdata = 0;    // boolean; set to true if we get data
1056                 clr_fl( child->read_data_fd, O_NONBLOCK );
1057
1058                 // Read a request from the parent, via a pipe, into a growing_buffer.
1059                 while( (n = read( child->read_data_fd, buf, READ_BUFSIZE-1 )) > 0 ) {
1060                         buf[n] = '\0';
1061                         osrfLogDebug( OSRF_LOG_MARK, "Prefork child read %d bytes of data", n );
1062                         if( !gotdata ) {
1063                                 set_fl( child->read_data_fd, O_NONBLOCK );
1064                                 gotdata = 1;
1065                         }
1066                         buffer_add_n( gbuf, buf, n );
1067                 }
1068
1069                 if( errno == EAGAIN )
1070                         n = 0;
1071
1072                 if( errno == EPIPE ) {
1073                         osrfLogDebug( OSRF_LOG_MARK, "C child attempted read on broken pipe, exiting..." );
1074                         break;
1075                 }
1076
1077                 int terminate_now = 0;     // Boolean
1078
1079                 if( n < 0 ) {
1080                         osrfLogWarning( OSRF_LOG_MARK,
1081                                 "Prefork child read returned error with errno %d", errno );
1082                         break;
1083
1084                 } else if( gotdata ) {
1085                         // Process the request
1086                         osrfLogDebug( OSRF_LOG_MARK, "Prefork child got a request.. processing.." );
1087                         terminate_now = prefork_child_process_request( child, gbuf->buf );
1088                         buffer_reset( gbuf );
1089                 }
1090
1091                 if( terminate_now ) {
1092                         // We're terminating prematurely -- presumably due to a fatal error condition.
1093                         osrfLogWarning( OSRF_LOG_MARK, "Prefork child terminating abruptly" );
1094                         break;
1095                 }
1096
1097                 if( i < child->max_requests - 1 ) {
1098                         // Report back to the parent for another request.
1099                         size_t msg_len = 9;
1100                         ssize_t len = write(
1101                                 child->write_status_fd, "available" /*less than 64 bytes*/, msg_len );
1102                         if( len != msg_len ) {
1103                                 osrfLogError( OSRF_LOG_MARK,
1104                                         "Drone terminating: unable to notify listener of availability: %s",
1105                                         strerror( errno ));
1106                                 buffer_free( gbuf );
1107                                 osrf_prefork_child_exit( child );
1108                         }
1109                 }
1110         }
1111
1112         buffer_free( gbuf );
1113
1114         osrfLogDebug( OSRF_LOG_MARK, "Child with max-requests=%d, num-served=%d exiting...[%ld]",
1115                 child->max_requests, i, (long) getpid());
1116
1117         osrf_prefork_child_exit( child );
1118 }
1119
1120 /**
1121         @brief Add a prefork_child to the end of the active list.
1122         @param forker Pointer to the prefork_simple that owns the list.
1123         @param child Pointer to the prefork_child to be added.
1124 */
1125 static void add_prefork_child( prefork_simple* forker, prefork_child* child ) {
1126
1127         if( forker->first_child == NULL ) {
1128                 // Simplest case: list is initially empty.
1129                 forker->first_child = child;
1130                 child->next = child;
1131                 child->prev = child;
1132         } else {
1133                 // Find the last node in the circular list.
1134                 prefork_child* last_child = forker->first_child->prev;
1135
1136                 // Insert the new child between the last and first children.
1137                 last_child->next = child;
1138                 child->prev      = last_child;
1139                 child->next      = forker->first_child;
1140                 forker->first_child->prev = child;
1141         }
1142 }
1143
1144 /**
1145         @brief Delete and destroy a dead child from our list.
1146         @param forker Pointer to the prefork_simple that owns the dead child.
1147         @param pid Process ID of the dead child.
1148
1149         Look for the dead child first in the list of active children.  If you don't find it
1150         there, look in the list of idle children.  If you find it, remove it from whichever
1151         list it's on, and destroy it.
1152 */
1153 static void del_prefork_child( prefork_simple* forker, pid_t pid ) {
1154
1155         osrfLogDebug( OSRF_LOG_MARK, "Deleting Child: %d", pid );
1156
1157         prefork_child* cur_child = NULL;
1158
1159         // Look first in the active list
1160         if( forker->first_child ) {
1161                 cur_child = forker->first_child; /* current pointer */
1162                 while( cur_child->pid != pid && cur_child->next != forker->first_child )
1163                         cur_child = cur_child->next;
1164
1165                 if( cur_child->pid == pid ) {
1166                         // We found the right node.  Remove it from the list.
1167                         if( cur_child->next == cur_child )
1168                                 forker->first_child = NULL;    // only child in the list
1169                         else {
1170                                 if( forker->first_child == cur_child )
1171                                         forker->first_child = cur_child->next;  // Reseat forker->first_child
1172
1173                                 // Stitch the adjacent nodes together
1174                                 cur_child->prev->next = cur_child->next;
1175                                 cur_child->next->prev = cur_child->prev;
1176                         }
1177                 } else
1178                         cur_child = NULL;  // Didn't find it in the active list
1179         }
1180
1181         if( ! cur_child ) {
1182                 // Maybe it's in the idle list.  This can happen if, for example,
1183                 // a child is killed by a signal while it's between requests.
1184
1185                 prefork_child* prev = NULL;
1186                 cur_child = forker->idle_list;
1187                 while( cur_child && cur_child->pid != pid ) {
1188                         prev = cur_child;
1189                         cur_child = cur_child->next;
1190                 }
1191
1192                 if( cur_child ) {
1193                         // Detach from the list
1194                         if( prev )
1195                                 prev->next = cur_child->next;
1196                         else
1197                                 forker->idle_list = cur_child->next;
1198                 } // else we can't find it
1199         }
1200
1201         // If we found the node, destroy it.
1202         if( cur_child )
1203                 prefork_child_free( forker, cur_child );
1204 }
1205
1206 /**
1207         @brief Create and initialize a prefork_child.
1208         @param forker Pointer to the prefork_simple that will own the prefork_child.
1209         @param read_data_fd Used by child to read request from parent.
1210         @param write_data_fd Used by parent to write request to child.
1211         @param read_status_fd Used by parent to read status from child.
1212         @param write_status_fd Used by child to write status to parent.
1213         @return Pointer to the newly created prefork_child.
1214
1215         The calling code is responsible for freeing the prefork_child by calling
1216         prefork_child_free().
1217 */
1218 static prefork_child* prefork_child_init( prefork_simple* forker,
1219         int read_data_fd, int write_data_fd,
1220         int read_status_fd, int write_status_fd ) {
1221
1222         // Allocate a prefork_child -- from the free list if possible, or from
1223         // the heap if necessary.  The free list is a non-circular, singly-linked list.
1224         prefork_child* child;
1225         if( forker->free_list ) {
1226                 child = forker->free_list;
1227                 forker->free_list = child->next;
1228         } else
1229                 child = safe_malloc( sizeof( prefork_child ));
1230
1231         child->pid              = 0;
1232         child->read_data_fd     = read_data_fd;
1233         child->write_data_fd    = write_data_fd;
1234         child->read_status_fd   = read_status_fd;
1235         child->write_status_fd  = write_status_fd;
1236         child->max_requests     = forker->max_requests;
1237         child->appname          = forker->appname;  // We don't make a separate copy
1238         child->keepalive        = forker->keepalive;
1239         child->next             = NULL;
1240         child->prev             = NULL;
1241
1242         return child;
1243 }
1244
1245 /**
1246         @brief Terminate all child processes and clear out a prefork_simple.
1247         @param prefork Pointer to the prefork_simple to be cleared out.
1248
1249         We do not deallocate the prefork_simple itself, just its contents.
1250 */
1251 static void prefork_clear( prefork_simple* prefork, bool graceful ) {
1252
1253         // always de-register routers before killing child processes (or waiting
1254         // for them to complete) so that new requests are directed elsewhere.
1255         osrf_prefork_register_routers(global_forker->appname, true);
1256
1257         while( prefork->first_child ) {
1258
1259                 if (graceful) {
1260                         // wait for at least one active child to become idle, then repeat.
1261                         // once complete, all children will be idle and cleaned up below.
1262                         osrfLogInfo(OSRF_LOG_MARK, "graceful shutdown waiting...");
1263                         check_children(prefork, 1);
1264
1265                 } else {
1266                         // Kill and delete all the active children
1267                         kill( prefork->first_child->pid, SIGKILL );
1268                         del_prefork_child( prefork, prefork->first_child->pid );
1269                 }
1270         }
1271
1272         if (graceful) {
1273                 osrfLogInfo(OSRF_LOG_MARK,
1274                         "all active children are now idle in graceful shutdown");
1275         }
1276
1277         // Kill all the idle prefork children, close their file
1278         // descriptors, and move them to the free list.
1279         prefork_child* child = prefork->idle_list;
1280         prefork->idle_list = NULL;
1281         while( child ) {
1282                 prefork_child* temp = child->next;
1283                 kill( child->pid, SIGKILL );
1284                 prefork_child_free( prefork, child );
1285                 child = temp;
1286         }
1287         //prefork->current_num_children = 0;
1288
1289         // Physically free the free list of prefork_children.
1290         child = prefork->free_list;
1291         prefork->free_list = NULL;
1292         while( child ) {
1293                 prefork_child* temp = child->next;
1294                 free( child );
1295                 child = temp;
1296         }
1297
1298         // Close the Jabber connection
1299         client_free( prefork->connection );
1300         prefork->connection = NULL;
1301
1302         // After giving the child processes a second to terminate, wait on them so that they
1303         // don't become zombies.  We don't wait indefinitely, so it's possible that some
1304         // children will survive a bit longer.
1305         sleep( 1 );
1306         while( (waitpid( -1, NULL, WNOHANG )) > 0 ) {
1307                 --prefork->current_num_children;
1308         }
1309
1310         free( prefork->appname );
1311         prefork->appname = NULL;
1312 }
1313
1314 /**
1315         @brief Destroy and deallocate a prefork_child.
1316         @param forker Pointer to the prefork_simple that owns the prefork_child.
1317         @param child Pointer to the prefork_child to be destroyed.
1318 */
1319 static void prefork_child_free( prefork_simple* forker, prefork_child* child ) {
1320         close( child->read_data_fd );
1321         close( child->write_data_fd );
1322         close( child->read_status_fd );
1323         close( child->write_status_fd );
1324
1325         // Stick the prefork_child in a free list for potential reuse.  This is a
1326         // non-circular, singly linked list.
1327         child->prev = NULL;
1328         child->next = forker->free_list;
1329         forker->free_list = child;
1330 }