#
include
<stdio.h>
#
include
<stdlib.h>
#
include
<unistd.h>
#
include
<errno.h>
#define PIPE_READ 0
#define PIPE_WRITE 1
string f(string s) {
int inputPipe[2];
int outputPipe[2];
pid_t childPid;
char c;
string result;
if
(pipe(inputPipe) < 0 || pipe(outputPipe) < 0) {
perror(
"Error creating pipes"
);
return
""
;
}
if
((childPid = fork()) == -1) {
perror(
"Error creating child process"
);
return
""
;
}
else
if
(childPid == 0) {
if
(dup2(inputPipe[PIPE_READ], STDIN_FILENO) < 0) {
perror(
"Error redirecting standard input"
);
exit
(errno);
}
if
(dup2(outputPipe[PIPE_WRITE], STDOUT_FILENO) < 0) {
perror(
"Error redirecting standard output"
);
exit
(errno);
}
if
(dup2(outputPipe[PIPE_WRITE], STDERR_FILENO) < 0) {
perror(
"Error redirecting standard error"
);
exit
(errno);
}
close(inputPipe[PIPE_READ]);
close(inputPipe[PIPE_WRITE]);
close(outputPipe[PIPE_READ]);
execl(
"/bin/sh"
,
"sh"
,
"-c"
, s.c_str(), NULL);
perror(
"Error executing child process"
);
exit
(errno);
}
else
{
close(inputPipe[PIPE_READ]);
close(outputPipe[PIPE_WRITE]);
write(inputPipe[PIPE_WRITE], s.c_str(), s.size());
while
(read(outputPipe[PIPE_READ], &c, 1) > 0) {
result += c;
}
close(inputPipe[PIPE_WRITE]);
close(outputPipe[PIPE_READ]);
waitpid(childPid, NULL, 0);
}
return
result;
}