pipe-posix.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2014 Hugh 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. return fwrite(data, 1, len, pp->file);
  81. }