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 II<br />

}<br />

/* child */<br />

signal (SIGTTIN, sigintHandler);<br />

setpgrp(0, getpid()); /* place child in new process group */<br />

printf("enter a string: ");<br />

scanf ( "%s", str); /* try to read from control terminal */<br />

printf("you entered %s\n", str);<br />

} else<br />

wait(&status); /* wait for child to terminate */<br />

void sigintHandler()<br />

{<br />

printf("attempted inappropriate read from control terminal\n");<br />

exit(1) ;<br />

}<br />

enter a string: attempted inappropriate read from control terminal<br />

PIPES<br />

Interprocess communication mechanism that allow two or more processes to send information to each o<strong>the</strong>r.<br />

Used to connect standard output of one utility to standard input of ano<strong>the</strong>r.<br />

$ who | wc -1<br />

Both <strong>the</strong> writer process and <strong>the</strong> reader process of a pipeline execute concurrently, a pipe automatically buffers <strong>the</strong><br />

output of <strong>the</strong> writer and suspends <strong>the</strong> writer if <strong>the</strong> pipe gets too full.<br />

UNNAMED PIPES<br />

pipe(fd) - unidirectional communication link<br />

fd[0]----------------------------------------------------<br />

write end | . |--->pipe--->| . | read end<br />

fd[l]-----------------------------------<br />

For bidirectional communication use two pipes<br />

/* talk.c */<br />

#include <br />

#define READ 0<br />

#define WRITE 1<br />

char* phrase = "a line of text for talk";<br />

main() {<br />

int fd[2], nread;<br />

char str[100];<br />

}<br />

pipe(fd); /* create unnamed pipe */<br />

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

close(fd[READ]); /* close unused end */<br />

write(fd[WRITE], phrase, strlen(phrase)+1);<br />

close(fd[WRITE]); /* close used end */<br />

}<br />

else<br />

{/* parent reader */<br />

close(fd[WRITE]); /* close unused end */<br />

nread = read(fd[READ], str, 100);<br />

printf("read %d bytes: %s\n", nread, str);<br />

close(fd[READ]); /* close used end */<br />

}<br />

128

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

Saved successfully!

Ooh no, something went wrong!