pipe-posix.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Copyright (c) 2023 Lain Bailey <[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 <stdio.h>
  17. #include <sys/wait.h>
  18. #include "bmem.h"
  19. #include "pipe.h"
  20. struct os_process_pipe {
  21. bool read_pipe;
  22. FILE *file;
  23. };
  24. os_process_pipe_t *os_process_pipe_create(const char *cmd_line,
  25. const char *type)
  26. {
  27. struct os_process_pipe pipe = {0};
  28. struct os_process_pipe *out;
  29. if (!cmd_line || !type) {
  30. return NULL;
  31. }
  32. pipe.file = popen(cmd_line, type);
  33. pipe.read_pipe = *type == 'r';
  34. if (pipe.file == (FILE *)-1 || pipe.file == NULL) {
  35. return NULL;
  36. }
  37. out = bmalloc(sizeof(pipe));
  38. *out = pipe;
  39. return out;
  40. }
  41. int os_process_pipe_destroy(os_process_pipe_t *pp)
  42. {
  43. int ret = 0;
  44. if (pp) {
  45. int status = pclose(pp->file);
  46. if (WIFEXITED(status))
  47. ret = (int)(char)WEXITSTATUS(status);
  48. bfree(pp);
  49. }
  50. return ret;
  51. }
  52. size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len)
  53. {
  54. if (!pp) {
  55. return 0;
  56. }
  57. if (!pp->read_pipe) {
  58. return 0;
  59. }
  60. return fread(data, 1, len, pp->file);
  61. }
  62. size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data,
  63. size_t len)
  64. {
  65. /* XXX: unsupported on posix */
  66. UNUSED_PARAMETER(pp);
  67. UNUSED_PARAMETER(data);
  68. UNUSED_PARAMETER(len);
  69. return 0;
  70. }
  71. size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data,
  72. size_t len)
  73. {
  74. if (!pp) {
  75. return 0;
  76. }
  77. if (pp->read_pipe) {
  78. return 0;
  79. }
  80. size_t written = 0;
  81. while (written < len) {
  82. size_t ret = fwrite(data + written, 1, len - written, pp->file);
  83. if (!ret)
  84. return written;
  85. written += ret;
  86. }
  87. return written;
  88. }