16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Processes II<br />

/* connect.c - equivalent to command line pipe */<br />

#include <br />

#define READ 0<br />

#define WRITE 1<br />

main(int argc, char *argv[])<br />

{<br />

int fd[2], pipe(FILE *fd); /* create unnamed pipe */<br />

}<br />

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

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

dup2(fd[WRITE],1); /* duplicated used end to stdout */<br />

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

execlp(argv[1], argv[1], NULL); /* execute writer program */<br />

fprintf(stderr, "connect"); /* should never execute */<br />

}<br />

else<br />

{ /* child reader */<br />

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

dup2(fd[READ],0); /* duplicated used end to stdout */<br />

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

execlp(argv[2], argv[2], NULL); /* execute writer program */<br />

fprintf(stderr, "connect"); /* should never execute */<br />

}<br />

connect who wc<br />

NAMED PIPES - FIFO (first in first out)<br />

Advantages:<br />

- have a name that exists in file system<br />

- may be used by unrelated processes<br />

- exist until explicitly deleted<br />

$ mknod mypipe p OR $ mkfifo mypipe<br />

mknod(argv[l], S_IFIFO, 0);<br />

chrnod(argv[l], 0660);<br />

If a process tries to open a named pipe for read-only and no process writing, <strong>the</strong> reader will wait until a process<br />

opens it for writing.<br />

(If O_NDELAY is set <strong>the</strong>n open succeeds immediately).<br />

If a process tries to open a named pipe for write-only and no process reading, <strong>the</strong> writer will wait until a process<br />

opens it for reading.<br />

(If O_NDELAY is set <strong>the</strong>n open fails immediately).<br />

/* reader.c */<br />

#include <br />

#include <br />

#include <br />

#include <br />

int mkfifo(char *name)<br />

{<br />

char str[100];<br />

}<br />

sprintf(str, "mkfifo %s", name);<br />

return(system(str));<br />

/* read NULL terminated line into str from fd */<br />

129

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

Saved successfully!

Ooh no, something went wrong!