16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Processes I<br />

Executed in child process to overlay itself <strong>with</strong> a specified binary program file.<br />

So:<br />

Cost of fork:<br />

Exec:<br />

produces a child process different from parent.<br />

copies all instructions and data of parent, only to be overlaid by exec. Some VM versions<br />

of UNIX use "copy-on-write" <strong>with</strong> parent and child processes sharing pages till<br />

overwritten (e.g. by exec) does NOT change semantics of fork.<br />

all executions on UNIX (apart from booting) are achieved by exec.<br />

Parent and child<br />

- are clones (except for pid)<br />

- share wd (working directory) (and 1 or 2 o<strong>the</strong>r things)<br />

- share open files<br />

The child typically does: exec<br />

e.g.<br />

if ((child-id = fork()) ! = 0)<br />

{ /*parent * /<br />

/* assume> 0 */<br />

foo = wait(&status); /* and returns status */<br />

}<br />

else<br />

{ /* child: execute 'ls' */<br />

execl("/bin/ls", "ls", "-l", NULL);<br />

exit(1); /* could not exec */<br />

}<br />

int execl(path, arg0, arg1, ..., argn, NULL);<br />

| | |<br />

binary prog file name local utility child may process <strong>the</strong>se via argc, argv of its “main”<br />

/* argv[argc] may not necessarily = NULL;<br />

use argc to count arg's ra<strong>the</strong>r than look for NULL */<br />

/* environment pointed to by environ is also accessible by child */<br />

The exec family:<br />

Argument Environment Path<br />

Format Passing Search?<br />

execl list auto no<br />

execv array* auto no<br />

execle list manual# no<br />

execve array* manual no<br />

execlp list auto yes+<br />

execvp array* auto yes<br />

* if no. of arg is unknown at compile time (c.f. "argv")<br />

# manually passing an environment pointer instead of automatically using environ<br />

+ e.g., /bin:/usr/bin:/usr/me/bin::<br />

execv<br />

will execute <strong>the</strong> file if it is a binary OR a shell command file.<br />

- testenv program<br />

main(argc,argv,envp)<br />

int argc; char * argv[]; char * envp[];<br />

{<br />

int cntr;<br />

printf("%d\n",argc);<br />

for (cntr = 0; cntr < argc; cntr++)<br />

{<br />

95

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!