Forking question

So I have this that is basically a shell. Anyway, if you enter in a & after your command, the command should run in the background, like in a bash shell. Well I'm not actually sure if it's functioning correct. It looks as if it might be, but then again it looks like it might not be. I'm still pretty new to the linux world so any pointers would be cool. Here's the section I'm working with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int main(int argc, char *argv[])
{
char inputBuffer[MAX_LINE]; // buffer to hold the command entered
int background;         // equals 1 if a command is followed by '&'
char *args[MAX_LINE/+1];// command line has max of 40 arguments 
pid_t pid;                // return code from fork()    

while (1) { // endless while, program terminates normally inside setup
     background = 0;
     printf(" COMMAND->\n");
     setup(inputBuffer,args,&background);    // get next command 

     /* Forks a child process */
     pid = fork();
     if(pid < 0) //Error occurred
       {
	 printf("Fork Failed");
	 return 1;
       }
     else if (pid == 0) //Child process
       {
	 execvp(args[0], args);
       }
     else
       {
	 printf("Child's PID is: %d\n",pid);
       }
     if(background == 0)
       {
	 wait(NULL);
       }
    }  // end while
}


What this should do is fork a new process, execute the command, and wait until it's done executing if background == 0. The background bit doesn't make too much sense to me, and the else of the large if doesn't really make sense to me either. I was following the format of a similar program in the book I have, but I couldn't find any real explanation behind it.
Running a command in a terminal is a blocking operation, running with the & runs in seperate process. The wait when background is 0 simulates running a command normally.
But wouldn't the fork() call make it run in a separate process already?
Yes, hence the wait to simulate the blocking of the running command.
Topic archived. No new replies allowed.