popen.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <signal.h>
  6. #define TEST(r, f, x, m) ( \
  7. ((r) = (f)) == (x) || \
  8. (printf(__FILE__ ":%d: %s failed (" m ")\n", __LINE__, #f, r, x), err++, 0) )
  9. #define TEST_E(f) ( (errno = 0), (f) || \
  10. (printf(__FILE__ ":%d: %s failed (errno = %d)\n", __LINE__, #f, errno), err++, 0) )
  11. #define TEST_S(s, x, m) ( \
  12. !strcmp((s),(x)) || \
  13. (printf(__FILE__ ":%d: [%s] != [%s] (%s)\n", __LINE__, s, x, m), err++, 0) )
  14. static sig_atomic_t got_sig;
  15. static void handler(int sig)
  16. {
  17. got_sig = 1;
  18. }
  19. int main(void)
  20. {
  21. int i;
  22. char foo[6];
  23. char cmd[64];
  24. int err = 0;
  25. FILE *f;
  26. TEST_E(f = popen("echo hello", "r"));
  27. TEST_E(fgets(foo, sizeof foo, f));
  28. TEST_S(foo, "hello", "child process did not say hello");
  29. TEST(i, pclose(f), 0, "exit status %04x != %04x");
  30. signal(SIGUSR1, handler);
  31. snprintf(cmd, sizeof cmd, "read a ; test \"x$a\" = xhello && kill -USR1 %d", getpid());
  32. TEST_E(f = popen(cmd, "w"));
  33. TEST_E(fputs("hello", f) >= 0);
  34. TEST(i, pclose(f), 0, "exit status %04x != %04x");
  35. signal(SIGUSR1, SIG_DFL);
  36. TEST(i, got_sig, 1, "child process did not send signal (%i!=%i)");
  37. return err;
  38. }