Docsity

Fork And Exec Functions-Network Programming-Lecture Slides, Slides of Network Programming

Partial preview of the text

Download Fork And Exec Functions-Network Programming-Lecture Slides and more Slides Network Programming in PDF only on Docsity!

Network

Programming(Lecture

fork^

and^

exec

Functions

fork

is^ that

it^ is^ called

once^

but^ it^

returns

twice.

It^ returns

once^

in^ the

calling

process

(called

the

parent)

with^ a

return

value

that^ is

the^ process

ID^ of

the^ newly

created

process

(the^ child).

It^ also

returns

once^

in^ the

child,

with^ a

return

value^

of^ 0.^ Hence,

the^ return

value

tells^ the

process

whether

it^ is^ the

parent

or^ the

child.

#include^ <unistd.h>pid_t^ fork(void);

Returns:^0

in^ child,^ process

ID^ of^ child

in^ parent,

‐^1 on^ error docsity.com

fork^

and^

exec

Functions

A^ process

makes

a^ copy

of^ itself

so^ that

one^ copy

can^ handle

one^ operation

while

the^ other

copy^

does

another

task,^

typical

for^ network

servers.

A^ process

wants

to^ execute

another

program.

Since

the^ only

way^ to

create

a^ new

process

is^ by^ calling

fork,^ the

process

first^ calls

fork^ to

make

a^ copy

of

itself,^

and^ then

one^ of

the^ copies

calls^ exec

to^ replace

itself^ with

the^ new

program.

fork^

and^

exec

Functions

executable

program

file^ on

disk^ can

be^ executed

by^ Unix

is^ for^

an^ existing

process

to^ call

one^ of

the

six^ exec

functions. exec

replaces

the^ current

process

image

with^ the

new^ program

file. ^ The

process

ID^ does

not^ change.

We^ refer

to^ the

process

that^ calls

exec^ as

the^ calling

process

and

the^ newly

executed

program

as^ the

new^ program.

new

process

is^ not

created

six^ exec

functions

#include^ <unistd.h>int^ execl^ (const

char^ *pathname,

const^ char

arg0,^ ...^ /

(char^ *)^0 */^ );

int execv (const

char^ *pathname,

char^ *const

argv[]);

int^ execle^ (const

char^ *pathname,

const^ char

arg0,^ ... /^ (char^ *)^

0,^ char^ *const envp[]

*/^ );

int execve (const

char^ *pathname,

char^ *const

argv[],^ char

*const^ envp[]);

int execlp (const

char^ *filename,

const^ char

arg0,^ ...^ /

(char^ *)^0 */

);

int execvp (const

char^ *filename,

char^ *const

argv[]);

All^ six^ return:

‐^1 on^ error,

no^ return^ on

success

These functions return to the caller only if an error occurs. Otherwise, control passes to the start ofthe new program.

Concurrent

Servers

when

a^ client

request

can^ take

longer

to^ service,

we^ do

not^ want

to^ tie

up^ a^ single

server

with^ one

client. want

to^ handle

multiple

clients

at^ the

same

time. The simplest

way^ to

write

a^ concurrent

server

under

Unix^ is

to^ fork

a^ child

process

to^ handle

each^ client.

Status

of^ client/server

after

return

from

accept

Status

of^ client/server

after

fork

returns