Skip to content

Instantly share code, notes, and snippets.

@jontonsoup
Created October 23, 2012 04:37
Show Gist options
  • Save jontonsoup/3936708 to your computer and use it in GitHub Desktop.
Save jontonsoup/3936708 to your computer and use it in GitHub Desktop.
void RunCmdPipe(commandT* cmd1, commandT* cmd2)
{
pid_t child;
int status = -1;
int pipe_status = -1;
int pid = 0;
fprintf (stdout,"executing %s () %s \n", cmd1->name, cmd2->argv[0]);
if ((child = fork()) > 0) // the shell parent process
{
fgJobPid = child;
fprintf (stdout,"waiting in super parent \n");
do
{
pid = waitpid(child, &status, 0);
} while (pid > 0);
status = WEXITSTATUS(status);
fprintf (stdout,"done in super parent \n");
// RunCmd(cmd2);
fflush(stdout);
}
else if (child == 0) // the pipe (parent)child process
{
// set the group id to the pid so it can be killed properly
if (setpgid(0, 0) != 0)
PrintPError("Error setting child gid\n");
// if the command could not be resolved, argc is set to 0
pid_t pipes_child;
fprintf (stdout,"setting pipe \n");
int fd[2];
pipe(fd);
if ((pipes_child = fork()) > 0){
// the pipe parent
// close(fd[1]); //close read from pipe, in parent
// dup2(fd[0], STDIN_FILENO); // Replace stdout with the write end of the pipe
// close(fd[0]);
fprintf (stdout,"waiting %s in pipe parent\n", cmd2->argv[0]);
// do
// {
// fprintf (stdout,"waiting %s in pipe parent...\n", cmd2->argv[0]);
pid = waitpid(pipes_child, &pipe_status, 0);
// } while (pid > 0);
pipe_status = WEXITSTATUS(pipe_status);
fprintf (stdout,"executing %s in pipe parent\n", cmd2->argv[0]);
// char readbuffer[80];
// int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
// printf("%i\n", nbytes);
// printf("%s\n", readbuffer);
fprintf (stdout,"exiting parent\n");
exit(pipe_status);
}
else if (pipes_child == 0) // the pipes child process
{
fprintf (stdout,"executing %s in pipe child: %i \n", cmd1->argv[0], cmd1->argc);
// close(fd[0]);
// dup2(fd[1], STDOUT_FILENO);
// close(fd[1]);
if(cmd1->argc > 0)
{
fprintf (stdout,"exec in child %s %s\n", cmd1->argv[0], cmd1->argv[1], cmd1->argv[2]);
pipe_status = execv(cmd1->argv[0], cmd1->argv);
}
else if (cmd1->argc == 0)
{
printf("./tsh-ref: line 1: %s: No such file or directory\n", cmd1->name);
}
fprintf (stdout,"exiting\n");
exit(pipe_status);
}
}
} /* RunCmdPipe */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment