Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4.  
  5. #include <string>
  6. #include <iostream>
  7.  
  8. int error_check( int result, std::string text )
  9. {
  10. if ( result == -1 )
  11. throw text ;
  12.  
  13. return result ;
  14. }
  15.  
  16. template < typename Input, typename Output >
  17. void check( std::string name, Input input, Output output )
  18. {
  19. int infd[2] ;
  20.  
  21. error_check( pipe( infd ), "Error: pipe failed." ) ;
  22.  
  23.  
  24. int outfd[2] ;
  25. error_check( pipe( outfd ), "Error: pipe failed." ) ;
  26.  
  27. pid_t cpid = error_check( fork(), "Error: fork failed." ) ;
  28.  
  29. // child
  30. if ( cpid == 0 )
  31. {
  32. close( infd[1] ) ;
  33. close( outfd[0] ) ;
  34.  
  35. dup2( infd[0], STDIN_FILENO ) ;
  36. dup2( outfd[1], STDOUT_FILENO ) ;
  37.  
  38. close( infd[0] ) ;
  39. close( outfd[1] ) ;
  40.  
  41. error_check(
  42. execl( "./main", "main", static_cast<char *>(nullptr) )
  43. , "Error: exec failed." ) ;
  44.  
  45. }
  46. // parent
  47. else
  48. {
  49.  
  50. close( infd[0] ) ;
  51. close( outfd[1] ) ;
  52.  
  53. int in = dup( STDIN_FILENO ) ;
  54. int out = dup( STDOUT_FILENO ) ;
  55.  
  56. dup2( outfd[0], STDIN_FILENO ) ;
  57. dup2( infd[1], STDOUT_FILENO ) ;
  58.  
  59. input() ;
  60. bool result = output() ;
  61.  
  62. dup2( in, STDIN_FILENO ) ;
  63. dup2( out, STDOUT_FILENO ) ;
  64.  
  65. std::cout << name << " : " << (result ? "Accepted" : "Wrong Answer") << std::endl ;
  66. }
  67.  
  68. }
  69.  
  70. int main()
  71. try {
  72.  
  73. check( "YES test",
  74. [](){ std::cout << "1" << std::endl ;},
  75. [](){
  76. std::string output ;
  77. std::cin >> output ;
  78. return output == "YES" ;
  79. } ) ;
  80.  
  81. check( "NO test",
  82. [](){ std::cout << "0" << std::endl ; },
  83. [](){
  84. std::string output ;
  85. std::cin >> output ;
  86. return output == "NO" ;
  87. } ) ;
  88.  
  89. } catch ( std::string text )
  90. {
  91. std::cerr << text << std::endl ;
  92. return 1 ;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement