UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2007-03-05 02:55 PM

sangfroid
Member
Registered: 2006-09-18
Posts: 29

Re: main program died during fork

Hi,
   I am supposed to write a shell which can run command like ls |wc

I created pipe , forked  a child...but when i run the program, after i execute that piece of code, the main program exits....

i think i am missing something...

if (!fork()) {
            close(1);       
            dup(pfds[1]);   
            close(pfds[0]); 
            execlp("ls", "ls", NULL);
        } else {
            close(0);       
            dup(pfds[0]);  
            close(pfds[1]); 
            execlp("wc", "wc", "-c", NULL);
        }

i think i need to fork twice and run the commands in separate child...but i am confused how to do it .

Offline

#2 2007-03-05 07:30 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: main program died during fork

Yeah, you're having the parent process exec*() into the "wc" process, so of course
when that exits, there's nothing left...  Yes, as you said, you need another fork() in
the parent (the parent is the one that gets a non-zero result from fork()), if you want
to keep the parent around...  Basically, change your "else" to "else if (!fork())"...  (Of
course, this is totally ignoring failures, but you seem to be doing that anyway...)
Then, in your parent process (the one that doesn't take that if() case), you probably
want to just wait*() for the kids to finish...

Offline

Board footer

Powered by FluxBB