proc.c
// Create a new process copying p as the parent.
// Sets up stack to return as if from system call.
// Caller must set state of returned proc to RUNNABLE.
Create a new process copying p as the parent.
Sets up stack to return as if from system call.
Caller must set state of returned proc to RUNNABLE.
Create a new process copying p as the parent . Sets up stack to return as if from system call . Caller must set state of returned proc to RUNNABLE .
int
fork(void)
{
  int i, pid;
  struct proc *np;
  if((np = allocproc()) == 0)
    return -1;
  if((np->pgdir = copyuvm(proc->pgdir, proc->sz)) == 0){
    kfree(np->kstack);
    np->kstack = 0;
    np->state = UNUSED;
  acquire(&ptable.lock);
  AddFreeList(np);
  release(&ptable.lock);
    return -1;
  }
  np->sz = proc->sz;
  np->parent = proc;
  *np->tf = *proc->tf;
  np->uid = proc->uid;
  np->gid = proc->gid;
  np->priority = 1;
  np->tf->eax = 0;
  for(i = 0; i < NOFILE; i++)
    if(proc->ofile[i])
      np->ofile[i] = filedup(proc->ofile[i]);
  np->cwd = idup(proc->cwd);
  safestrcpy(np->name, proc->name, sizeof(proc->name));
  pid = np->pid;
  acquire(&ptable.lock);
  np->state = RUNNABLE;
    AddReadyList(np);
  release(&ptable.lock);
  return pid;
}
int fork ( void ) { int i , pid ; struct proc * np ; if ( ( np = allocproc ( ) ) == 0 ) return -1 ; if ( ( np -> pgdir = copyuvm ( proc -> pgdir , proc -> sz ) ) == 0 ) { kfree ( np -> kstack ) ; np -> kstack = 0 ; np -> state = UNUSED ; acquire ( & ptable . lock ) ; AddFreeList ( np ) ; release ( & ptable . lock ) ; return -1 ; } np -> sz = proc -> sz ; np -> parent = proc ; * np -> tf = * proc -> tf ; np -> uid = proc -> uid ; np -> gid = proc -> gid ; np -> priority = 1 ; np -> tf -> eax = 0 ; for ( i = 0 ; i < NOFILE ; i ++ ) if ( proc -> ofile [ i ] ) np -> ofile [ i ] = filedup ( proc -> ofile [ i ] ) ; np -> cwd = idup ( proc -> cwd ) ; safestrcpy ( np -> name , proc -> name , sizeof ( proc -> name ) ) ; pid = np -> pid ; acquire ( & ptable . lock ) ; np -> state = RUNNABLE ; AddReadyList ( np ) ; release ( & ptable . lock ) ; return pid ; }
Create a new process copying p as the parent.
Create a new process copying p as the parent .
// Allocate process. // Copy process state from p. ///allocating uid and gid // Clear %eax so that fork returns 0 in the child. // lock to force the compiler to emit the np->state write last.