main.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <inttypes.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <uv.h>
  6. uv_loop_t *loop;
  7. uv_process_t child_req;
  8. uv_process_options_t options;
  9. void cleanup_handles(uv_process_t *req, int64_t exit_status, int term_signal) {
  10. fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
  11. uv_close((uv_handle_t*) req->data, NULL);
  12. uv_close((uv_handle_t*) req, NULL);
  13. }
  14. void invoke_cgi_script(uv_tcp_t *client) {
  15. size_t size = 500;
  16. char path[size];
  17. uv_exepath(path, &size);
  18. strcpy(path + (strlen(path) - strlen("cgi")), "tick");
  19. char* args[2];
  20. args[0] = path;
  21. args[1] = NULL;
  22. /* ... finding the executable path and setting up arguments ... */
  23. options.stdio_count = 3;
  24. uv_stdio_container_t child_stdio[3];
  25. child_stdio[0].flags = UV_IGNORE;
  26. child_stdio[1].flags = UV_INHERIT_STREAM;
  27. child_stdio[1].data.stream = (uv_stream_t*) client;
  28. child_stdio[2].flags = UV_IGNORE;
  29. options.stdio = child_stdio;
  30. options.exit_cb = cleanup_handles;
  31. options.file = args[0];
  32. options.args = args;
  33. // Set this so we can close the socket after the child process exits.
  34. child_req.data = (void*) client;
  35. int r;
  36. if ((r = uv_spawn(loop, &child_req, &options))) {
  37. fprintf(stderr, "%s\n", uv_strerror(r));
  38. return;
  39. }
  40. }
  41. void on_new_connection(uv_stream_t *server, int status) {
  42. if (status == -1) {
  43. // error!
  44. return;
  45. }
  46. uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
  47. uv_tcp_init(loop, client);
  48. if (uv_accept(server, (uv_stream_t*) client) == 0) {
  49. invoke_cgi_script(client);
  50. }
  51. else {
  52. uv_close((uv_handle_t*) client, NULL);
  53. }
  54. }
  55. int main() {
  56. loop = uv_default_loop();
  57. uv_tcp_t server;
  58. uv_tcp_init(loop, &server);
  59. struct sockaddr_in bind_addr;
  60. uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
  61. uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0);
  62. int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
  63. if (r) {
  64. fprintf(stderr, "Listen error %s\n", uv_err_name(r));
  65. return 1;
  66. }
  67. return uv_run(loop, UV_RUN_DEFAULT);
  68. }