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.

fd[l] for writing */<br />

i.e. where read & write are used <strong>with</strong> a normal file's fd, we can likewise use read/write <strong>with</strong> a pipe fd.<br />

! Strategy for pipe manipulation/usage:<br />

1. create <strong>the</strong> pipe<br />

2. fork to create <strong>the</strong> (communicating) child, e.g. reading<br />

3. in child: e.g., close writing end of and o<strong>the</strong>r preparation<br />

4. in child: 'exec' child process (? utility)<br />

5. in parent: close reading end of pipe<br />

6. if a second child is to write to <strong>the</strong> pipe<br />

create it ('fork')<br />

make any special preparations<br />

'exec' <strong>the</strong> child<br />

else if parent is to write to pipe<br />

go ahead - WRITE!<br />

The above illustrate <strong>the</strong> need to separate 'fork' and 'exec' as two separate system calls<br />

int fd[2];<br />

pipe(fd);<br />

if (fork() != 0) { /*parent*/<br />

close(fd[0]; /* close reading end */<br />

write to fd[l] ...<br />

}else { /* child code */<br />

close fd[l]; /* close write */<br />

exec(whatever)...<br />

}<br />

/* overlay*/<br />

/* reads from fd[0]; */<br />

Processes I<br />

'fork' generates a clone <strong>with</strong> an exact copy of "per process file table", The fd[0], fd[l] file descriptors (table<br />

subscripts) refer to a clone's local table.<br />

int fd[2];<br />

pipe (fd) ;<br />

if (fork()! = 0) { /* parent */<br />

close (fd[0]); /* reading end */<br />

if (fork() == 0){ /* 2nd child */<br />

exec(foo); /* write to fd[l] */<br />

} else /* first child */<br />

close (fd[l]); /* close writing end */<br />

exec(whatever)... /* overlay */<br />

/* reads from fd[0] */<br />

}<br />

Standard utilities use<br />

stdin (fd=0)<br />

stdout (fd=l)<br />

To make use of <strong>the</strong> unmodified utilities, we use "dup" and "dup2",<br />

e.g.<br />

pipe (pfd); /* int pfd[2] */<br />

if fork() !=0) { /* parent */<br />

close(pfd[0); /* close <strong>the</strong> reading end */<br />

write to pfd[l]...<br />

} else { /* child code */<br />

close(0); /* close stdin */<br />

close(pfd[l]); /* close writing end */<br />

dup2(pfd[0],0); /* copy <strong>the</strong> reading end over stdin */<br />

close(pfd[0]); /* close <strong>the</strong> original reading end */<br />

exec(utility); /* reads from stdin fd=0 */<br />

}<br />

97

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

Saved successfully!

Ooh no, something went wrong!