1 of 20

1

CS644 week 5:

Interprocess communication

2 of 20

How to pass data between processes?

2

3 of 20

Interprocess communication

Today:

  • Pipes
  • Shared memory
  • Semaphores

Later:

  • Unix domain sockets
  • Signals

3

4 of 20

Pipe – one-way data flow (read/write)

4

Pipes

5 of 20

ps aux | grep myprocess

5

Pipes

6 of 20

int pipe2(

int pipefd[2],

int flags,

)

6

Pipes

7 of 20

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

8 of 20

Pipes are useful for related processes

8

Pipes

9 of 20

Shared memory

9

10 of 20

Shared memory – pass data without copying

10

Shared memory

11 of 20

int shm_open(

const char* name,

int flag,

mode_t mode,

)

11

Shared memory

12 of 20

int shm_unlink(

const char* name,

)

12

Shared memory

13 of 20

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

14 of 20

Problem – how to synchronize access?

14

Shared memory

15 of 20

Problem – how to synchronize access?

Use a named semaphore

15

Shared memory

16 of 20

sem_t* sem_open(

const char* name,

int oflag,

mode_t mode,

)

16

Shared memory

17 of 20

int sem_wait(sem_t*);

int sem_trywait(sem_t*);

int sem_post(sem_t*);

17

Shared memory

18 of 20

sem_t* sem_unlink(

const char* name,

)

18

Shared memory

19 of 20

In-class exercises

19

20 of 20

Let's put it all together into an example program.

20

In-class exercises