Thread: fork() a background task

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    7

    fork() a background task

    I am building a small shell for school. I have the forground tasks handled with fork(), execvp() and waitpid().

    Now I need to handle background tasks. I'm handling parsing out the & at the end.

    I need to know how to send the child to the background

    AND

    how to set up an asynchronous waitpid() so that I know when the task completes. (I have to print usage information which I believe I can process the same way as my foreground tasks.


    Thanks!

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by HighSeraphim View Post
    I need to know how to send the child to the background
    Note that "foreground" and "background" are shell concepts, and have nothing to do with the OS itself. How you send a process to the background is completely up to you.

    The real difference between a foreground process and a background process is that for a foreground process, the shell calls wait() to wait for the child to finish. For a background process, simply don't do that.

    When a child process dies, your shell will receive a SIGCHLD signal. You can install a signal handler for this signal, and call wait() from within this handler to reap the dead child (actually, you want to call wait() in a loop until no more processes can be reaped, since more than one child might have died). Beyond that, it's fire-and-forget. Fork off the child just like any other process, then go about your business.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Where do a task get "wakeuped", blocked, preempted?
    By micke_b in forum Linux Programming
    Replies: 4
    Last Post: 12-28-2007, 04:49 PM
  2. Letting a program run as a task ( background )
    By GanglyLamb in forum C# Programming
    Replies: 5
    Last Post: 12-01-2005, 08:52 AM
  3. fork(), exit() - few questions!
    By s3t3c in forum C Programming
    Replies: 10
    Last Post: 11-30-2004, 06:58 AM
  4. Daemon programming: allocated memory vs. fork()
    By twisgabak in forum Linux Programming
    Replies: 2
    Last Post: 09-25-2003, 02:53 PM
  5. Scheduling Algo
    By BigDaddyDrew in forum C++ Programming
    Replies: 41
    Last Post: 03-08-2003, 11:00 AM