Process.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "util/events/libuv/UvWrapper.h"
  16. #include "memory/Allocator.h"
  17. #include "util/events/libuv/EventBase_pvt.h"
  18. #include "util/events/Process.h"
  19. #include "util/Bits.h"
  20. #include "util/Identity.h"
  21. struct Process_pvt
  22. {
  23. uv_process_t proc;
  24. struct Allocator* alloc;
  25. Identity
  26. };
  27. static void onFree2(uv_handle_t* process)
  28. {
  29. Allocator_onFreeComplete((struct Allocator_OnFreeJob*) process->data);
  30. }
  31. static int onFree(struct Allocator_OnFreeJob* job)
  32. {
  33. struct Process_pvt* p = Identity_check((struct Process_pvt*) job->userData);
  34. uv_process_kill(&p->proc, SIGTERM);
  35. p->proc.data = job;
  36. uv_close((uv_handle_t*)&p->proc, onFree2);
  37. return Allocator_ONFREE_ASYNC;
  38. }
  39. int Process_spawn(char* binaryPath, char** args, struct EventBase* base, struct Allocator* alloc)
  40. {
  41. struct EventBase_pvt* ctx = EventBase_privatize(base);
  42. int i;
  43. for (i = 0; args[i]; i++) ;
  44. char** binAndArgs = Allocator_calloc(alloc, sizeof(char*), i+2);
  45. for (i = 0; args[i]; i++) {
  46. binAndArgs[i+1] = args[i];
  47. }
  48. binAndArgs[0] = binaryPath;
  49. binAndArgs[i+1] = NULL;
  50. struct Process_pvt* p = Allocator_calloc(alloc, sizeof(struct Process_pvt), 1);
  51. p->alloc = alloc;
  52. Identity_set(p);
  53. Allocator_onFree(alloc, onFree, p);
  54. uv_stdio_container_t files[] = {
  55. { .flags = UV_IGNORE },
  56. { .flags = UV_INHERIT_FD, .data.fd = 1 },
  57. { .flags = UV_INHERIT_FD, .data.fd = 2 },
  58. };
  59. uv_process_options_t options = {
  60. .file = binaryPath,
  61. .args = binAndArgs,
  62. .flags = UV_PROCESS_WINDOWS_HIDE,
  63. .stdio = files,
  64. .stdio_count = 3
  65. };
  66. return uv_spawn(ctx->loop, &p->proc, options);
  67. }
  68. char* Process_getPath(struct Allocator* alloc)
  69. {
  70. char path[4096];
  71. size_t sz = 4096;
  72. uv_exepath(path, &sz);
  73. char* out = Allocator_malloc(alloc, sz+1);
  74. Bits_memcpy(out, path, sz);
  75. out[sz] = 0;
  76. return out;
  77. }