Background processes in a dummy shell...

Hey guys,
I am writing a very simple dummy shell in C++ and I am having trouble getting a process to run in the background. First of all, the shell has to recognize when I input a "&" at the end of the command, then it has to stick it in the background of the shell.

I understand that if I want a process to run in the background, then I don't wait on it... but that's the thing. I don't know how to impliment this.

Any help would be awesome. Thanks!:smiley:

  1. Do it with the shell
./myprogram &

will run my myprogram in the background

  1. Do it in the program
int main(int argc,char **argv)
{
     pid_t pid=fork();
     if (pid)
     {
            printf("started as %d\n",(int)pid);
            exit(0);
     }

     rest of program
}

I'm sorry I didn't elaborate more.
First of all, my main function take no arguments. The way my program runs is after compile, I type the name of the executable in Unix and it starts the shell with a prompt waiting for the user to enter a command.

I can enter a command for a program in the same file directory and have it run in the foreground fine. But when I enter the same command with "&" after it, it still runs in the foreground.

I don't think I am isolating the "&" correctly. But even if I do, how do I NOT run this process in the foreground?

Thanks for the help.:smiley:

How are you running the program?

fork()
execlp()
wait()

or

system()

I am using fork()
execv() and wait()

What do you think "in the foreground" means?

For example, not calling a blocking wait would help.

One simple way to do background processes is by:

the parent (that is your main program) forks a child, and then the child forks its own child

you'll have something like this:

Loop:
----------------------------
parent
|
child
|
child's child (aka grandChild)
-----------------------------

the parent WILL NOT wait() for its child, this can be a simple condition, test if there is & appended or not

child WILL wait() for its child (grandChild)

you'll be doing this in a loop, and since the parent wont be waiting for its child the parent can fork() other childern, and they will fork() their own childern.

This is me trying to explain it, or here's a simple psuedocode that shows how it is done:

main()
{
     // parent running
     while(1)
     {
         child = fork();
         if(child==0)
         {
            // child running
            grandChild = fork();

            if(grandChild==0)
            {
                   // grand child running
                   exec();
            }

            wait();         // child must wait for grandChild
       }
            if()              // a condition to test for &
                  wait(); // doesn't exist then wait
   }
}