pipe.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. {
  41. va_list va_args;
  42. struct dstr tmp = {0};
  43. va_start(va_args, format);
  44. dstr_vprintf(&tmp, format, va_args);
  45. da_insert(args->arguments, args->arguments.num - 1, &tmp.array);
  46. va_end(va_args);
  47. }
  48. size_t os_process_args_get_argc(struct os_process_args *args)
  49. {
  50. /* Do not count terminating NULL. */
  51. return args->arguments.num - 1;
  52. }
  53. char **os_process_args_get_argv(const struct os_process_args *args)
  54. {
  55. return args->arguments.array;
  56. }
  57. void os_process_args_destroy(struct os_process_args *args)
  58. {
  59. if (!args)
  60. return;
  61. for (size_t idx = 0; idx < args->arguments.num; idx++)
  62. bfree(args->arguments.array[idx]);
  63. da_free(args->arguments);
  64. bfree(args);
  65. }