-
Notifications
You must be signed in to change notification settings - Fork 2
/
pipe.cpp
97 lines (88 loc) · 2.32 KB
/
pipe.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* $Id$
This file is a part of ponder, a English/American checkers game.
Copyright (c) 2006, 2007 Quux Information.
Gong Jie <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
/** @file pipe.cpp
* @brief Create pipe.
*/
#include <cstring>
#include <string>
#include "pipe.hpp"
namespace checkers
{
std::pair<int, int> pipe_open(const std::string& path)
{
int fd[2][2];
pid_t pid;
size_t i;
for (i = 0; i < sizeof(fd) / sizeof(fd[0]); ++i)
{
if (pipe(fd[i]) < 0)
{
/** @throw std::runtime_error when pipe()
* failed.
*/
throw std::runtime_error(
std::string("pipe() failed: ")
+ std::strerror(errno));
}
}
if ((pid = fork()) < 0)
{
/// @throw std::runtime_error when fork() failed.
throw std::runtime_error(
std::string("fork() failed: ")
+ std::strerror(errno));
}
else if (0 == pid)
{
// Child
close(fd[0][1]);
close(fd[1][0]);
if (STDIN_FILENO != fd[0][0])
{
if (dup2(fd[0][0], STDIN_FILENO)
!= STDIN_FILENO)
{
throw std::runtime_error(
std::string("dup2() failed: ")
+ std::strerror(errno));
}
}
if (STDOUT_FILENO != fd[1][1])
{
if (dup2(fd[1][1], STDOUT_FILENO)
!= STDOUT_FILENO)
{
throw std::runtime_error(
std::string("dup2() failed: ")
+ std::strerror(errno));
}
}
if (execl(path.c_str(), path.c_str(), NULL) < 0)
{
throw std::runtime_error(
std::string("execl() failed: ")
+ std::strerror(errno));
}
}
// Parent
close(fd[0][0]);
close(fd[1][1]);
return std::pair<int, int>(fd[1][0], fd[0][1]);
}
}
// End of file