pipe.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2023 Dennis Sädtler <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "pipe.h"
  17. #include "darray.h"
  18. #include "dstr.h"
  19. struct os_process_args {
  20. DARRAY(char *) arguments;
  21. };
  22. struct os_process_args *os_process_args_create(const char *executable)
  23. {
  24. struct os_process_args *args = bzalloc(sizeof(struct os_process_args));
  25. char *str = bstrdup(executable);
  26. da_push_back(args->arguments, &str);
  27. /* Last item in argv must be NULL. */
  28. char *terminator = NULL;
  29. da_push_back(args->arguments, &terminator);
  30. return args;
  31. }
  32. void os_process_args_add_arg(struct os_process_args *args, const char *arg)
  33. {
  34. char *str = bstrdup(arg);
  35. /* Insert before NULL list terminator. */
  36. da_insert(args->arguments, args->arguments.num - 1, &str);
  37. }
  38. void os_process_args_add_argf(struct os_process_args *args, const char *format, ...)
  39. {
  40. va_list va_args;
  41. struct dstr tmp = {0};
  42. va_start(va_args, format);
  43. dstr_vprintf(&tmp, format, va_args);
  44. da_insert(args->arguments, args->arguments.num - 1, &tmp.array);
  45. va_end(va_args);
  46. }
  47. size_t os_process_args_get_argc(struct os_process_args *args)
  48. {
  49. /* Do not count terminating NULL. */
  50. return args->arguments.num - 1;
  51. }
  52. char **os_process_args_get_argv(const struct os_process_args *args)
  53. {
  54. return args->arguments.array;
  55. }
  56. void os_process_args_destroy(struct os_process_args *args)
  57. {
  58. if (!args)
  59. return;
  60. for (size_t idx = 0; idx < args->arguments.num; idx++)
  61. bfree(args->arguments.array[idx]);
  62. da_free(args->arguments);
  63. bfree(args);
  64. }