drain.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdlib.h>
  2. #include <reproc/drain.h>
  3. #include <reproc/reproc.h>
  4. // Shows the output of the given command using `reproc_drain`.
  5. int main(int argc, const char **argv)
  6. {
  7. (void) argc;
  8. reproc_t *process = NULL;
  9. char *output = NULL;
  10. int r = REPROC_ENOMEM;
  11. process = reproc_new();
  12. if (process == NULL) {
  13. goto finish;
  14. }
  15. r = reproc_start(process, argv + 1, (reproc_options){ 0 });
  16. if (r < 0) {
  17. goto finish;
  18. }
  19. r = reproc_close(process, REPROC_STREAM_IN);
  20. if (r < 0) {
  21. goto finish;
  22. }
  23. // `reproc_drain` reads from a child process and passes the output to the
  24. // given sinks. A sink consists of a function pointer and a context pointer
  25. // which is always passed to the function. reproc provides several built-in
  26. // sinks such as `reproc_sink_string` which stores all provided output in the
  27. // given string. Passing the same sink to both output streams makes sure the
  28. // output from both streams is combined into a single string.
  29. reproc_sink sink = reproc_sink_string(&output);
  30. // By default, reproc only redirects stdout to a pipe and not stderr so we
  31. // pass `REPROC_SINK_NULL` as the sink for stderr here. We could also pass
  32. // `sink` but it wouldn't receive any data from stderr.
  33. r = reproc_drain(process, sink, REPROC_SINK_NULL);
  34. if (r < 0) {
  35. goto finish;
  36. }
  37. printf("%s", output);
  38. r = reproc_wait(process, REPROC_INFINITE);
  39. if (r < 0) {
  40. goto finish;
  41. }
  42. finish:
  43. // Memory allocated by `reproc_sink_string` must be freed with `reproc_free`.
  44. reproc_free(output);
  45. reproc_destroy(process);
  46. if (r < 0) {
  47. fprintf(stderr, "%s\n", reproc_strerror(r));
  48. }
  49. return abs(r);
  50. }