0

Here is my code for the evaluate function, which is called in the main.

void eval(char *cmdline)
{
 char *argv[MAXARGS]; /* argv for execve() */
 int bg;              /* should the job run in bg or fg? */
 pid_t pid;           /* process id */

bg = parseline(cmdline, argv);
    struct job_t tempJob;
if (builtin_cmd(argv) == 0)
{
    if ((pid = fork()) == 0)
    {   /* child runs user job */
        if (execve(argv[0], argv, environ) < 0)
        {
            printf("%s: Command not found.\n", argv[0]);
            exit(0);
        }
    }

    if (!bg)
    {   /* parent waits for fg job to terminate */
       int status;


        if (waitpid(pid, &status, 0) < 0)
            unix_error("waitfg: waitpid error");
    }
    else         /* otherwise, don’t wait for bg job */
       {
            printf("%d %s", pid, cmdline);
       }
}

    return;
}

Now when I run a background job, I expect that the pid of the job get printed twice twice, once in parent and once for child.I just need to understand what is going on in the code. It works the way it is supposed to but why?

user3213348
  • 255
  • 1
  • 5
  • 14

1 Answers1

1

Both the parent and child return from fork, but the condition == 0 is true only for the child:

if ((pid = fork()) == 0)

Thus only the child runs this:

    if (execve(argv[0], argv, environ) < 0)

execve replaces the current process, and thus does not return if there is no error, i.e., the child's execution of this program ends either here or at the exit(0); that follows from the error condition.

The rest of the function is run only by the parent in all cases.

Arkku
  • 41,011
  • 10
  • 62
  • 84
  • but why does the child only run a certain portion, doesn't fork replicate the two processes identically? – user3213348 Feb 24 '14 at 00:24
  • @user3213348 They split at your `if ((pid = fork()) == 0)` because only the child returns `0` from `fork`. `execve` causes the child never exit from the body of that `if` statement. – Arkku Feb 24 '14 at 00:27