I know this topic has been posted about quite a bit, but I'm looking to take it in a different direction. I would like to write a program that has shell piping functionality, i.e. cmd1 | cmd2 | cmd3 piping and redirects. I have read pages like this, this, and this for reference. And these solutions work great for "horizontal pipelining" but I would like to implement it "vertically". For my shell to be vertical, each 'command' process must have a different parent (the previous command). So, each command to be executed is spawned from the previous. The issue I have been having is that when I recurse in the child (rather than the parent like the examples), the program executes fine but then hangs and I must hit enter to reprompt my shell. I'm curious why this is different and how to fix this.
static void exec_pipeline(size_t pos, int in_fd) {
// Invalid Pipe has issues
if (newargv[pipe_commands[pos+1]] == NULL)
report_error_and_exit("Invalid pipe");
/* last command, pipe_command conatins indices of commands to execute */
if (pipe_commands[pos + 1] == 0) {
redirect(in_fd, STDIN_FILENO); /* read from in_fd, write to STDOUT */
execvp(newargv[pipe_commands[pos]], newargv + pipe_commands[pos]);
report_error_and_exit("execvp last command");
}
else { /* $ <in_fd cmds[pos] >fd[1] | <fd[0] cmds[pos+1] ... */
int fd[2]; /* output pipe */
if (pipe(fd) == -1)
report_error_and_exit("pipe");
switch(fork()) {
case -1:
report_error_and_exit("fork");
case 0: /* parent: execute the rest of the commands */
CHK(close(fd[1])); /* unused */
CHK(close(in_fd)); /* unused */
exec_pipeline(pos + 1, fd[0]); /* execute the rest */
default: /* child: execute current command `cmds[pos]` */
child = 1;
CHK(close(fd[0])); /* unused */
redirect(in_fd, STDIN_FILENO); /* read from in_fd */
redirect(fd[1], STDOUT_FILENO); /* write to fd[1] */
execvp(newargv[pipe_commands[pos]], newargv + pipe_commands[pos]);
report_error_and_exit("execvp");
}
}
}
void report_error_and_exit(const char *msg) {
perror(msg);
(child ? _exit : exit)(EXIT_FAILURE);
}
/* move oldfd to newfd */
void redirect(int oldfd, int newfd) {
if (oldfd != newfd) {
if (dup2(oldfd, newfd) != -1)
CHK(close(oldfd));
else
report_error_and_exit("dup2");
}
}
CHK is a lot like assert, defined in a file called CHK.h, and looks like this if you're curious:
do {if((x) == -1)\
{fprintf(stderr,"In file %s, on line %d:\n",__FILE__,__LINE__);\
fprintf(stderr,"errno = %d\n",errno);\
perror("Exiting because");\
exit(1);\
}\
} while(0)