Piping, Forking, and Gathering execvp's Output
Hey guys,
I'm building a minishell in C(for unix). I'm doing command expansion, so lets say I have:
it works fine, however if I then do this:
it prints:
I think I've figured it out, when I'm reading the output of echo(from my pipe), echo does not output any null terminator, so I go on for a bit until I run into one. This results in me picking up a bunch of garbage. Currently my read loop looks like this:
Code:
bytes_read = read(fd[0],buf,BUF_SIZE);
while(bytes_read > 0)
{
/* HERES THE TROUBLE! */
bytes_read = read(fd[0], buf, BUF_SIZE);
if (bytes_read == -1) perror("read");
}
close(fd[0]);
So here it picks up a bit extra. I was thinking of simply turning the last '\n' into a 0, but I can't figure out how to start at the end of the string, and work my way back(if I did I probably wouldn't be having this problem), and if I start at the beginning and work forward, I may remove a newline that was meant to be there.
I was also thinking that I could write a null character right after echo executes, however, I don't know how I'd do this. When echo writes, it looks like this:
Code:
cpid = fork();
if (cpid < 0) {
perror ("fork");
free(args);
return;
}
/* Check for who we are! */
if (cpid == 0) {
/* We are the child! */
/* Turning stdout into pipe output if needed */
if((dup2(outFD, 1)) < 0)
{
perror("dup");
return;
}
execvp(args[0], args);
perror ("exec");
exit (127);
last_exit_status = 127;
}
dprintf(outFD, 0);
/* Have the parent wait for child to complete */
if(waitFlag)
{
if (wait (&status) < 0) perror ("wait");
last_exit_status = ((WEXITSTATUS(status) || !WIFEXITED(status)) ? 127 : 0);
}
I was thinking the dprintf(outFD, 0) line would work, but it doesn't seem to be the case. How do I mark the end of execvp's output?
Thanks for the help, if you guys want me to post my code I will.