Unix Programming - Re: Need help with piping

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > November 2004 > Re: Need help with piping





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Re: Need help with piping
Fletcher Glenn

2004-11-19, 5:51 pm



Diane M. Napolitano wrote:
> Hi, everyone. I've been reading through this group's archives (among
> other places) looking for a solution to my problem, and I've tried many
> different approaches, to no avail. As you might have been able to
> predict, I am writing a very basic shell for my OS class at my university.
> I have the shell written and working, and now I have to implement
> redirecion and piping. However, no matter what I try, I can't get the
> piping to work. I've been testing with the command (under Linux) dmesg |
> more, and rather than dmesg's output being piped into more, the shell
> goes into an endless loop, spawning new instances of both the parent and
> dmesg every so often (A previous version of my program did this with
> more, as well). I'm not asking anyone to do my homework for me; I've
> been working on this since Sunday and I'm stuck. I hope someone out
> there wouldn't mind taking a look at my code and pointing me in the right
> direction...?
>
> Here's my code that does the actual piping. The commands are passed in as
> structs with members command.name (the name of the command, ex. "ls") and
> command.argv (its arguments), as well as command.argc (# of arguments):
>
> int runPipedCommands(command_t *cmd, command_t *cmd2)
> {
> int fd[2], pid[2];
> pipe(fd);
> if ((pid[0]=fork())==0) //parent?
> {
> close(fd[1]);
> dup2(fd[0], 0);
> close(fd[0]);
> execv(cmd2->name, cmd2->argv);
> waitpid(pid[0], NULL, WUNTRACED);
> }
> else
> {
> if ((pid[1]=fork())==0) //child?
> {
> close(fd[0]);
> dup2(fd[1], 1);
> close(fd[1]);
> execv(cmd->name, cmd->argv);
> }
> else
> {
> close(fd[0]);
> close(fd[1]);
> waitpid(pid[1], NULL, WUNTRACED);
> }
> }
> return 0;
> }
>
> Thanks in advance.


Before you can use a file descriptor as a dup2 target, you must close it
if it is open. In the case of zero and one, these descriptors are open.

--

Fletcber Glenn


Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com