JustJustin

Untitled

Oct 23rd, 2015
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. int fids[2][2];
  2.  
  3. if (0 != pipe(fids[0])) {
  4.     throw sys_error(errno, strerror(errno));
  5. }
  6. if (0 != pipe(fids[1])) {
  7.     int myerrno = errno;
  8.     close(fids[0][0]);
  9.     close(fids[0][1]);
  10.     throw sys_error(myerrno, strerror(myerrno));
  11. }
  12.  
  13. pid_t pid = fork();
  14. switch(pid)
  15. {
  16. case 0:
  17.     // Close read ends
  18.     close(fids[0][0]);
  19.     close(fids[1][0]);
  20.  
  21.     // Dup write ends to stdout
  22.     if (-1 == dup2(fids[0][1], STDOUT_FILENO)) {
  23.         _exit(1);
  24.     }
  25.     cerr << "about to test stdout" << endl; // this prints
  26.     cout << "Testing stdout!" << endl; // this doesn't. EPIPE here
  27.     cerr << "Testing stderr!" << endl; // obv doesn't
  28.  
  29.     exec(...);
  30.     _exit(1);
  31.     break;
  32. case -1:
  33.     int myno = errno;
  34.     // close everything
  35.     close(fids[0][0]);
  36.     close(fids[0][1]);
  37.     close(fids[1][0]);
  38.     close(fids[1][1]);
  39.     // error
  40.     throw sys_error(myno, strerror(myno));
  41.     break;
  42. }
  43. // this should be parent only
  44. // close write ends
  45. close(fids[0][1]);
  46. close(fids[1][1]);
  47.  
  48. wait(...)
Advertisement
Add Comment
Please, Sign In to add comment