Reputation: 235
I wrote a program that reads a bash file and execute the commands inside that file. I got the execution part working, but I can't seem to be able to redirect the command output to a pipe, then read from the pipe and print its content. I've read some topics on the subject but the solution do not seem to work. Here is the code,
int main(int argc, char * argv[]) {
int pipefd[2];
char buf[1024];
int bytes = 0;
for (int i = 1; i < argc; i++) { // reading file as argument one at a time
FILE * fp;
fp = fopen(argv[i], "r");
char * buffer = NULL;
size_t buf_size = 0;
char bufread[1024];
int bytes_read = 0;
while (getline( & buffer, &buf_size, fp) != EOF) {
pid_t pid;
pid = fork();
pipe(pipefd);
if (pid == 0) {
close(pipefd[0]);
dup2(pipefd[1], 1);
dup2(pipefd[1], 2);
close(pfd[1]);
int length = countWords(buffer);
char * init_argv[length + 2];
init_argv[0] = "sh";
init_argv[1] = "-c";
init_argv[2] = buffer;
init_argv[3] = NULL;
execv("/bin/bash", init_argv);
} else {
int status;
close(pfd[1]);
waitpid(pid, & status, 0);
while (read(pfd[0], bufread, sizeof(bufread)) != 0) {
fprintf(stdout, "%s\n", bufread);
}
}
}
}
}
return 0;
}
Why there isn't any output when this program is run with a valid file containing commands as argument? I know without the dup2 and close instructions, the program execute the commands so that is not the problem. As soon as I add the dup2 and close instruction to the program, I can't debug it anymore (it crash at execv).
Upvotes: 0
Views: 80
Reputation: 409
I'm not sure if this is the problem, but shouldn't the call pipe(pipefd);
be executed before the call to fork
?
As it is now, I think the parent and the child each create a different pipe, and they cannot use those pipes to communicate with one another, if that is what you want to do.
Upvotes: 2