pipe-posix.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 "bmem.h"
  18. #include "pipe.h"
  19. struct os_process_pipe {
  20. bool read_pipe;
  21. FILE *file;
  22. };
  23. os_process_pipe_t *os_process_pipe_create(const char *cmd_line,
  24. const char *type)
  25. {
  26. struct os_process_pipe pipe = {0};
  27. struct os_process_pipe *out;
  28. if (!cmd_line || !type) {
  29. return NULL;
  30. }
  31. pipe.file = popen(cmd_line, type);
  32. pipe.read_pipe = *type == 'r';
  33. if (pipe.file == (FILE*)-1 || pipe.file == NULL) {
  34. return NULL;
  35. }
  36. out = bmalloc(sizeof(pipe));
  37. *out = pipe;
  38. return out;
  39. }
  40. void os_process_pipe_destroy(os_process_pipe_t *pp)
  41. {
  42. if (pp) {
  43. pclose(pp->file);
  44. bfree(pp);
  45. }
  46. }
  47. size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len)
  48. {
  49. if (!pp) {
  50. return 0;
  51. }
  52. if (!pp->read_pipe) {
  53. return 0;
  54. }
  55. return fread(data, len, 1, pp->file);
  56. }
  57. size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data,
  58. size_t len)
  59. {
  60. if (!pp) {
  61. return 0;
  62. }
  63. if (pp->read_pipe) {
  64. return 0;
  65. }
  66. return fwrite(data, len, 1, pp->file);
  67. }