1 /* spawn - demo of the gras_agent_spawn function */
3 /* Copyright (c) 2007 Martin Quinson. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
10 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(Spawn);
12 /* Global private data */
19 static int father_cb_ping_handler(gras_msg_cb_ctx_t ctx, void *payload)
23 /* 1. Get the payload into the msg variable, and retrieve my caller */
24 int msg = *(int *) payload;
25 gras_socket_t expeditor = gras_msg_cb_ctx_from(ctx);
27 /* 2. Retrieve the father's state (globals) */
28 father_data_t *globals = (father_data_t *) gras_userdata_get();
31 /* 3. Log which client connected */
32 INFO3("Kid %s:%d pinged me with %d",
33 gras_socket_peer_name(expeditor), gras_socket_peer_port(expeditor),
36 /* 4. Change the value of the msg variable */
38 /* 5. Send it back as payload of a pong message to the expeditor */
40 gras_msg_send(expeditor, "pong", &msg);
42 /* 6. Deal with errors: add some details to the exception */
44 gras_socket_close(globals->sock);
45 RETHROW0("Unable to answer to my poor child: %s");
47 INFO2("Answered to %s:%d's request",
48 gras_socket_peer_name(expeditor), gras_socket_peer_port(expeditor));
50 /* 7. Tell GRAS that we consummed this message */
52 } /* end_of_father_cb_ping_handler */
54 int father(int argc, char *argv[])
56 father_data_t *globals;
63 /* 1. Init the GRAS infrastructure and declare my globals */
64 gras_init(&argc, argv);
65 globals = gras_userdata_new(father_data_t);
67 /* 2. Get args from the command line, if specified */
70 child_amount = atoi(argv[2]);
73 /* 3. Initialize my globals (mainly create my master socket) */
74 globals->sock = gras_socket_server(port);
77 /* 4. Register the known messages. */
78 spawn_register_messages();
80 /* 5. Register my callback */
81 gras_cb_register("ping", &father_cb_ping_handler);
83 /* 6. Spawn the kids */
84 INFO0("Spawn the kids");
85 for (i = 0; i < child_amount; i++) {
86 child_args = xbt_new0(char *, 3);
87 child_args[0] = xbt_strdup("child");
88 child_args[1] = bprintf("%d", port);
90 gras_agent_spawn("child", NULL, child, 2, child_args, NULL);
93 /* 7. Wait to be contacted be the kids */
94 while (globals->msg_got < child_amount)
95 gras_msg_handle(60.0);
96 INFO0("All kids gone. Leave now.");
98 /* 8. Free the allocated resources, and shut GRAS down */
99 gras_socket_close(globals->sock);
104 } /* end_of_father */