Lesson 3 of 15
fork()
The fork() System Call
fork() creates a new process by duplicating the calling process. The child is an almost exact copy of the parent — same memory, same open files, same code. Only a few things differ:
- The child gets a new PID
- The child's parent PID (ppid) is set to the parent's PID
- The child starts in READY state (not RUNNING)
- The child's CPU time counters are reset to 0
In the kernel, fork() calls copy_process(), which allocates a new task_struct and copies the parent's fields one by one.
Your Implementation
Write void my_fork(PCB *parent, PCB *child, int new_pid) that initializes child as a copy of parent with the new PID and READY state.
void my_fork(PCB *parent, PCB *child, int new_pid) {
child->pid = new_pid;
child->state = READY;
child->priority = parent->priority;
// copy name
char *s = parent->name, *d = child->name;
while (*s) *d++ = *s++;
*d = '\0';
}
After forking, print both parent and child with print_pcb.
Your Task
Implement my_fork that copies the parent PCB into the child, assigning the new PID and setting state to READY.
TCC compiler loading...
Loading...
Click "Run" to execute your code.