Presentation Transcript
Chapter 18 some additional notes…: Chapter 18 some additional notes… Interprocess Communication (IPC) in C
We can create processes using fork()
Need to exchange data and control information
Many options are available to use…
Pipes
Signals
Message Queues
Semaphores
Shared Memory
Sockets
We’ll look at two of them
pipes and sockets
Chapter 18 some additional notes…: Chapter 18 some additional notes… Pipe
Pipe can be used to transfer data
think of the C pipe like a conduit for data
Parent and child can both read/write from/to the pipe
Programmer decides:
Parent writes, child reads
Child writes, parent reads
Parent and child both read and write
this is the default
Pipe is available in the stdio.h
Syntax is straightforward, for example:
int fd[2]
pipe(fd) // pass integer array of size 2 - for file descriptors
Chapter 18 some additional notes…: Chapter 18 some additional notes… Pipe and Fork
Create the pipe first, then fork the child process
Parent Child
Kernal Pipe
Chapter 18 some additional notes…: Chapter 18 some additional notes… Pipe
Read from the pipe?
Can I read the data in the pipe more than once?
No
See pipe_read_test.c example
Write to the pipe?
Can I overwrite data that hasn’t been read yet?
No
See pipe_write_test.c example
Chapter 18 some additional notes…: Chapter 18 some additional notes… Overview of example code
~kcooper/public_html/teaching/3375/IPC_pipe/pipe.c
Here, parent writes to pipe, child reads from pipe
Create, initialize variables
Create the pipe
Create the child process with fork
If child
close write fd[1]
…
read from pipe
…
Else parent
close read fd[0]
…
write to pipe
… Reminder.
Parent and child are two separate processes that can be executed by the CPU
Chapter 18 some additional notes…: Chapter 18 some additional notes… Pipe call
pipe(fd), where fd is an integer array of size 2
fd[0] read or write?
fd[1] read or write?
Read call
read(fd[0],buf,100)
Write call
write(fd[1], “something to write ”, 19) or
write(fd[1], my_char_array, strlen(my_char_array))
fd[0] which file descriptor to use
buf where to store the read values
100 how many characters to read fd[1] which file descriptor to use
“something to write” what to write
19 how many characters to write
Chapter 18 some additional notes…: Chapter 18 some additional notes… Synchronizing the reads and writes?
A simple way is to use sleep call
simple
not very precise
If child writes and parent reads, then could use wait call in parent
simple
doesn’t work the other way around (parent writes, child reads)
More sophisticated solutions are possible
E.g., use signals
more advanced
Note. we’ll stay with the first two options
Slide8: Happy Halloween!