1
CS644 week 5:
Interprocess communication
How to pass data between processes?
2
Interprocess communication
Today:
Later:
3
Pipe – one-way data flow (read/write)
4
Pipes
ps aux | grep myprocess
5
Pipes
int pipe2(
int pipefd[2],
int flags,
)
6
Pipes
pipe2(fds, 0);
// check error
pid_t pid = fork();
// check error
if (pid == 0) {
// child - write to fds[1]�} else {
// parent - read from fds[0]�}
7
Pipes
Pipes are useful for related processes
8
Pipes
Shared memory
9
Shared memory – pass data without copying
10
Shared memory
int shm_open(
const char* name,
int flag,
mode_t mode,
)
11
Shared memory
int shm_unlink(
const char* name,
)
12
Shared memory
int fd = shm_open("/my-program",
O_CREAT | O_EXCL | O_RDWR, 0600);
// check error
ftruncate(fd, sizeof my_data_struct);
// check error
my_data_struct* s;
s = mmap(NULL, sizeof *s,
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
13
Shared memory
Problem – how to synchronize access?
14
Shared memory
Problem – how to synchronize access?
Use a named semaphore
15
Shared memory
sem_t* sem_open(
const char* name,
int oflag,
mode_t mode,
)
16
Shared memory
int sem_wait(sem_t*);
int sem_trywait(sem_t*);
int sem_post(sem_t*);
17
Shared memory
sem_t* sem_unlink(
const char* name,
)
18
Shared memory
In-class exercises
19
Let's put it all together into an example program.
20
In-class exercises