fork download
  1. //
  2. // WILL NOT WORK ON ideone.com!!! COMPILE ON YOUR OWN LINUX MACHINE USING
  3. //
  4. // gcc -std=gnu11 -Wall -Wextra -Wconversion -Werror -pedantic -pedantic-errors -o prog prog.c
  5. //
  6.  
  7. #include <alloca.h>
  8. #include <assert.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16.  
  17. void pputs(char const * const string) {
  18. printf("%d(%d): ", getpid(), getppid());
  19. puts(string);
  20. }
  21.  
  22. int main() {
  23. pputs(__FILE__);
  24. pputs("reading from stdin [press Enter]");
  25. assert(errno == 0);
  26. read(STDIN_FILENO, alloca(0x100), 0x100);
  27. assert(errno == 0);
  28. pputs("forking");
  29. if (fork()) {
  30. // parent
  31. sleep(1);
  32. pputs("slept one second");
  33. pputs("reading from stdin [should fail with EWOULDBLOCK]");
  34. assert(errno == 0);
  35. read(STDIN_FILENO, alloca(0x100), 0x100);
  36. assert(errno == EWOULDBLOCK);
  37. errno = 0;
  38. pputs(strerror(EWOULDBLOCK));
  39. } else {
  40. // child
  41. pputs("setting stdin to non-blocking");
  42. int const flags = fcntl(STDIN_FILENO, F_GETFL, 0);
  43. fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
  44. }
  45. pputs("exiting");
  46. exit(EXIT_SUCCESS);
  47. }
Runtime error #stdin #stdout #stderr 0s 15240KB
stdin
stdout
1310(1309): prog.cpp
1310(1309): reading from stdin [press Enter]
1310(1309): forking
1362(1310): setting stdin to non-blocking
1362(1310): exiting
1310(1309): prog.cpp
1310(1309): reading from stdin [press Enter]
1310(1309): forking
1310(1309): slept one second
1310(1309): reading from stdin [should fail with EWOULDBLOCK]
stderr
prog: prog.cpp:36: int main(): Assertion `errno == EWOULDBLOCK' failed.