4 – Inter-process Communication

Shared-Memory in *nix

Master program creates SHM.

Master program (creates SHM) function
shmid = shmget(IPC_PRIVATE, size, flags) creating shared memory region
shm = (int*) shmat(shmid, NULL, 0) attach shared memory to this process
while (shm[0] == 0) {...} shm[0] equals 1 if ready, 0 if not.
shmdt( (char*) shm ) detaches memory
shmctl( shmid, IPC_RMID, 0 ) IPC_RMID marks for destroying after last process detached

Slave program attaches to SHM.

Slave program function
scanf("%d", &shmid) shmid passed from master to slave
shm = shmat(...) attach
shm[0] = 1 informs master of completion
shmdt((char*) shm) detach

Pros

Cons

Passing messages

Direct communication

Indirect communication

Synchronization Behaviours

Q: What if you’re trying to receive a message but the sender hasn’t sent yet?

A: 2 methods of synchronization:

Sender doesn’t block unless buffer is full. Unless the sender requires an acknowledgement.

Pros

Cons

Unix Pipes |

Connects stdout of Process A to the WRITE end of the of the pipe, which passes on to the READ end of the pipe to stdin of Process B. Note it is FIFO.

Is a circular bounded byte buffer. Writers wait when buffer is full, readers wait when buffer is empty.

Its syscall in C is pipe(args[2]), where args[0] is the READ end and args[1] is the WRITE end.

// parent
close(pipeFd[READ_END]);
write(pipeFd[WRITE_END], str, strlen(str) + 1);
close(pipeFd[WRITE_END]);
//child
close(pipeFd[WRITE_END]);
read(pipeFd[READ_END], buf, sizeof(buf));
close(pipeFd[READ_END]);

Possible to change/attach the std__ communication channels to any one of the pipe ends.

Unix Signal