Download presentation
Presentation is loading. Please wait.
Published byEugenia Kelley Modified over 5 years ago
1
fork() and exec() David Ferry CSCI 3500 – Operating Systems
Saint Louis University St. Louis, MO 63103
2
CSCI 3500 - Operating Systems
Process Creation Two functions to create and initialize a new process: fork() – creates an identical clone of the calling process Creates a parent-child relationship Child is identical to the parent except for a new PID and the return value from fork(). Some process-specific info is modified as well (e.g. accounting). See docs for details. Implemented efficiently with lazy copy-on-write exec() – replaces existing process with another program CSCI Operating Systems
3
CSCI 3500 - Operating Systems
fork() I.e. a fork in the road int x = 10; int y = 20; fork(); if( child ) x = 30; fork() parent parent x = 10 child x = 30 time x = 10 x = 10 CSCI Operating Systems
4
CSCI 3500 - Operating Systems
fork() fork() is a unique function Called once, returns twice Return value in parent is the PID of the child Return value in the child is zero Can be useful for concurrent programming – two loosely related processes executing alongside one another parent ret = fork() time parent ret = child PID child ret = 0 CSCI Operating Systems
5
CSCI 3500 - Operating Systems
Lazy Copy-On-Write The “cloning” behavior of fork() makes it very efficient to implement. Very little needs to be changed immediately. Some things might never need to be changed. Use existing data until a write operation modifies it, then make a copy and modify the copy If you want to execute a whole new program, exec() will overwrite everything anyway, and we don’t want to do that twice .stack .stack .heap .heap .data .data .text .text CSCI Operating Systems
6
CSCI 3500 - Operating Systems
exec() Replaces process space with that of a new program Replaces contents of program with a new binary image Despite name, only makes a program eligible for execution Typical Usage: int ret = fork(); if ( ret == 0 ){ //child newCmd = … newArgv = … exec( newCmd, newArgv); } CSCI Operating Systems
7
CSCI 3500 - Operating Systems
wait() waitpid() and related functions wait for a child to finish executing: int ret = fork(); if ( ret == 0 ){ //child stuff } waitpid( ret, NULL, 0 ); Prevents parent from progressing until the child terminates. CSCI Operating Systems
8
CSCI 3500 - Operating Systems
kill() General purpose function for sending signals Good for event notification, but carry no information. Originally used to forcibly stop processes, but now an established method for inter-process communication. Many different signals with different meanings, see man 7 signal for details. kill( child_pid, SIGINT ) is same as CTRL-C CSCI Operating Systems
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.