50
Linux/UNIX Programming Linux/UNIX Programming Linux/UNIX Programming Linux/UNIX Programming APUE APUE APUE APUE (Interprocess Interprocess Communication) Communication) (Interprocess Interprocess Communication) Communication) 문양세 문양세 강원대학교 강원대학교 IT IT특성화대학 특성화대학 컴퓨터과학전공 컴퓨터과학전공

16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Linux/UNIX ProgrammingLinux/UNIX ProgrammingLinux/UNIX ProgrammingLinux/UNIX Programming

APUEAPUEAPUE APUE ((InterprocessInterprocess Communication)Communication)((InterprocessInterprocess Communication)Communication)

문양세문양세강원대학교강원대학교 ITIT특성화대학특성화대학 컴퓨터과학전공컴퓨터과학전공

Page 2: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

ContentsContentsAPUE (Interprocess Communication

Pipes

FIFOs

System V IPC

• Message Queues

• Shared Memoryy

• Semaphores

UNIX System Programmingby Yang-Sae MoonPage 2

Page 3: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

IPC using PipesIPC using PipesAPUE (Interprocess Communication

IPC using regular files

unrelated processes can share• unrelated processes can share

• fixed size

l k f h• lack of synchronization

IPC using pipes

• for transmitting data between related processes

• can transmit an unlimited amount of data

• automatic synchronization on open()

UNIX System Programmingby Yang-Sae MoonPage 3

Page 4: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Pipes in a UNIX ShellPipes in a UNIX ShellAPUE (Interprocess Communication

In a UNIX shell, the pipe symbol is: | (the vertical bar)

In a shell, UNIX pipes look like:

$ ls -alg | more

• where the standard output of the program at the left (i.e., the producer) becomes the p p g ( , p )standard input of the program at the right (i.e., the consumer).

We can have longer pipes:

$ i | tbl | | dit ff$ pic paper.ms | tbl | eqn | ditroff -ms

UNIX System Programmingby Yang-Sae MoonPage 4

Page 5: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Example (1/2)Example (1/2)APUE (Interprocess Communication

$ who | sort

pipewho sort

pipewho sort

write pointer ofth

read pointer of another process one process

UNIX System Programmingby Yang-Sae MoonPage 5

Page 6: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Example (2/2)Example (2/2)APUE (Interprocess Communication

UNIX System Programmingby Yang-Sae MoonPage 6

Page 7: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

IPC using PipesIPC using PipesAPUE (Interprocess Communication

Data transmitting

data is written into pipes using the write() system call• data is written into pipes using the write() system call

• data is read from a pipe using the read() system call

bl k h f ll• automatic blocking when full or empty

Types of pipes

• (unnamed) pipes

• named pipes (FIFOs)

UNIX System Programmingby Yang-Sae MoonPage 7

Page 8: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Pipes (1/4)Pipes (1/4)APUE (Interprocess Communication

In UNIX, pipes are the oldest form of IPC.

Limitations of Pipes:

• Half duplex (data flows in one direction)

• Can only be used between processes that have a common ancestor y p(Usually used between the parent and child processes)

• Processes cannot pass pipes and must inherit them from their parent

• If a process creates a pipe, all its children will inherit it

UNIX System Programmingby Yang-Sae MoonPage 8

Page 9: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Pipes (2/4)Pipes (2/4)APUE (Interprocess Communication

#include <unistd.h>

int pipe(int fd[2])int pipe(int fd[2])Returns: 0 if OK, -1 on error

Two file descriptors are returned through the fd argument

• fd[0]: can be used to read from the pipe, and

• fd[1]: can be used to write to the pipe

Anything that is written on fd[1] may be read by fd[0].y g f [ ] y y f [ ]

• This is of no use in a single process.

• However between processes it gives a method of communication• However, between processes, it gives a method of communication

The pipe() system call gives parent-child processes a way to communicate with each other

UNIX System Programmingby Yang-Sae MoonPage 9

communicate with each other.

Page 10: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Pipes (3/4)Pipes (3/4)APUE (Interprocess Communication

parent child:parent closes fd[0]

parent child:parent closes fd[1]parent closes fd[0]

child closes fd[1]p [ ]child closes fd[0]

parent child parent childp child p

fd[1] fd[0] fd[0] fd[1]

pipe

kernel

pipe

kernel

UNIX System Programmingby Yang-Sae MoonPage 10

e el

Page 11: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Pipes (4/4)Pipes (4/4)APUE (Interprocess Communication

Read from a pipe with write end closed: (fd[1]이 close된 경우)

returns 0 to indicate EOF• returns 0 to indicate EOF

Write to a pipe with read end closed: (fd[0]가 close된 경우)

• SIGPIPE generated,

• write() returns error (errno == EPIPE)

UNIX System Programmingby Yang-Sae MoonPage 11

Page 12: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: pipe.c (1/2): pipe.c (1/2)APUE (Interprocess Communication

#include <stdio.h> // pipe.c

#define READ 0#d fi WRITE 1#define WRITE 1

char* phrase = "Stuff this in your pipe and smoke it";

i ( ) {main( ) {int fd[2], bytesRead;char message[100];pipe(fd);if (f k() 0) { // hildif (fork() == 0) { // child

close(fd[READ]);write(fd[WRITE], phrase, strlen(phrase)+1);fprintf(stdout, "[%d, child] write completed.\n", getpid());l (fd[WRITE])close(fd[WRITE]);

}else { // parent

close(fd[WRITE]);b t R d d(fd[READ] 100)bytesRead = read(fd[READ], message, 100);fprintf(stdout, "[%d, parent] read completed.\n", getpid());printf("Read %d bytes: %s\n", bytesRead,message);close(fd[READ]);

}

UNIX System Programmingby Yang-Sae MoonPage 12

}}

Page 13: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: pipe.c (2/2): pipe.c (2/2)APUE (Interprocess Communication

실행 결과

UNIX System Programmingby Yang-Sae MoonPage 13

Page 14: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

ContentsContentsAPUE (Interprocess Communication

Pipes

FIFOs

System V IPC

• Message Queues

• Shared Memoryy

• Semaphores

UNIX System Programmingby Yang-Sae MoonPage 14

Page 15: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

FIFOs (1/3)FIFOs (1/3)APUE (Interprocess Communication

Pipes can be used only between related processes.(e.g., parent and child processes)(e.g., parent and child processes)

FIFOs are "named pipes" that can be used between unrelated processes.

A type of file

• stat.st_mode == FIFO

• Test with S_ISFIFO() macro

UNIX System Programmingby Yang-Sae MoonPage 15

Page 16: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

FIFOs (2/3)FIFOs (2/3)APUE (Interprocess Communication

#include <sys/types.h>#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);Returns: 0 if OK, -1 on error

Creating FIFOs is similar to creating a file.

• pathname: filename

• mode: permissons, same as for open() function

Using a FIFO is similar to using a file.g g

• we can open, close, read, write, unlink, etc., to the FIFO.

UNIX System Programmingby Yang-Sae MoonPage 16

Page 17: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

FIFOs (3/3)FIFOs (3/3)APUE (Interprocess Communication

if FIFO opened without O_NONBLOCK flag

an open for read only blocks until some other process opens the FIFO for writing• an open for read-only blocks until some other process opens the FIFO for writing

• an open for write-only blocks until some other process opens the FIFO for reading

if O_NONBLOCK is specified (nonblocking)

• an open for read-only returns immediately if no process has the FIFO open for writing

• an open for write-only returns an error (errno=ENXIO) if no process has the FIFO open for reading

Like a pipe, if we write to a FIFO that no process has open for reading, the signal SIGPIPE is generated.

When the last writer for a FIFO closes the FIFO, an end of file (EOF) is generated for the reader of the FIFO.

UNIX System Programmingby Yang-Sae MoonPage 17

Page 18: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Uses of FIFOsUses of FIFOsAPUE (Interprocess Communication

Used by shell commands to pass data from one shell pipeline to another, without creating intermediate files.without creating intermediate files.

Used in client-server application to pass data between clients and server.

UNIX System Programmingby Yang-Sae MoonPage 18

Page 19: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Using FIFOs to Duplicate Output StreamsUsing FIFOs to Duplicate Output StreamsAPUE (Interprocess Communication

tee(1) copies its standard input to both its standard output and to the file named on its command line.

$ mkfifo fifo1$ mkfifo fifo1$ prog3 < fifo1 &$ prog1 < infile | tee fifo1 | prog2

prog3fifo1

infileprog1 tee

prog2

UNIX System Programmingby Yang-Sae MoonPage 19

prog2

Page 20: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

An Example using a FIFOAn Example using a FIFOAPUE (Interprocess Communication

UNIX System Programmingby Yang-Sae MoonPage 20

Page 21: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

ClientClient--Server Communication Using a FIFOServer Communication Using a FIFOAPUE (Interprocess Communication

Server creates a “well-known” FIFO to communicate with clients.

client

write requestq

.

.well-known

FIFOreadrequest

server..

clientwrite request

Problem: Server can't reply clients using a single “well-known” FIFO

UNIX System Programmingby Yang-Sae MoonPage 21

p y g g

Page 22: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

ContentsContentsAPUE (Interprocess Communication

Pipes

FIFOs

System V IPC

• Message Queues

• Shared Memoryy

• Semaphores (간단히)

UNIX System Programmingby Yang-Sae MoonPage 22

Page 23: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

System V IPCSystem V IPCAPUE (Interprocess Communication

Message Queues

• Send and receive amount of data called “messages”.g

• The sender classifies each message with a type.

Shared Memory

• Shared memory allows two or more processes to share a given region of memory.

• Readers and writers may use semaphore for synchronization.

Semaphores

• Process synchronization and resource management

• For example, a semaphore might be used to control access to a device like printer.

UNIX System Programmingby Yang-Sae MoonPage 23

Page 24: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Identifiers & KeysIdentifiers & KeysAPUE (Interprocess Communication

Identifier: each IPC structure has a nonnegative integer

Key: when creating an IPC structure, a key must be specified (key_t)

id = xxxget(key, …)

How to access the same IPC? key in a common header

• Define a key in a common header

• Client and server agree to use that key

• Server creates a new IPC structure using that key

P bl h th k i l d i • Problem when the key is already in use

− (msgget, semget, shmget returns error)

− Solution: delete existing key, create a new one again!

UNIX System Programmingby Yang-Sae MoonPage 24

g y g

Page 25: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

IPC System CallsIPC System CallsAPUE (Interprocess Communication

msg/sem/shm get

• Create new or open existing IPC structure. p g

• Returns an IPC identifier

msg/sem/shm ctl

• Determine status, set options and/or permissions

• Remove an IPC identifier

msg/sem/shm op

• Operate on an IPC identifier

• For example(Message queue)

− add new msg to a queue (msgsnd)

i f ( )

UNIX System Programmingby Yang-Sae MoonPage 25

− receive msg from a queue (msgrcv)

Page 26: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Permission StructurePermission StructureAPUE (Interprocess Communication

ipc_perm is associated with each IPC structure.

f h dDefines the permissions and owner.

struct ipc_perm {uid_t uid; /* owner's effective user id */gid_t gid; /* owner's effective group id */uid_t cuid; /* creator's effective user id */gid t cgid; /* creator's effective group id */gid_t cgid; / creator s effective group id /mode_t mode; /* access modes */ulong seq; /* slot usage sequence number */key_t key; /* key */

};

UNIX System Programmingby Yang-Sae MoonPage 26

Page 27: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Message Queues (1/2)Message Queues (1/2)APUE (Interprocess Communication

Linked list of messages

• Stored in kernel

• Identified by message queue identifier (in kernel)

msgget

• Create a new queue or open existing queue.

msgsnd

Add • Add a new message to a queue

msgrcvmsgrcv

• Receive a message from a queue

• Fetching order: based on type

UNIX System Programmingby Yang-Sae MoonPage 27

g yp

Page 28: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Message Queues (2/2)Message Queues (2/2)APUE (Interprocess Communication

Each queue has a structure

struct msqid_ds { struct ipc_perm msg_perm; struct msg *msg_first; /* ptr to first msg on queue */ struct msg *msg last; /* ptr to last msg on queue */struct msg msg_last; / ptr to last msg on queue / ulong msg_cbytes; /* current # bytes on queue */ ulong msg_qnum; /* # msgs on queue */ ulong msg_qbytes; /* max # bytes on queue */

/ /pid_t msg_lspid; /* pid of last msgsnd() */ pid_t msg_lrpid; /* pid of last msgrcv() */ time_t msg_stime; /* last-msgsnd() time */ time t msg rtime; /* last-msgrcv() time */time_t msg_rtime; / last msgrcv() time / time_t msg_ctime; /* last-change time */

};

We can get the structure using msgctl() function.

Actually, however, we don’t need to know the structure in detail.

UNIX System Programmingby Yang-Sae MoonPage 28

Page 29: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

msgget()msgget()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg h>#include <sys/msg.h>

int msgget(key_t key, int flag); Returns: msg queue ID if OK, -1 on error

Create new or open existing queue

flag : ipc_perm.mode

Examplemsg_qid = msgget(DEFINED_KEY, IPC_CREAT | 0666);

UNIX System Programmingby Yang-Sae MoonPage 29

Page 30: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

msgctl()msgctl()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg h>#include <sys/msg.h>

int msgctl(int msqid, int cmd, struct msqid_ds *buf); Returns: 0 if OK, -1 on error

Performs various operations on a queue

cmd = IPC_STAT:fetch the msqid_ds structure for this queue, storing it in buf

cmd = IPC_SET:set the following four fields from buf: msg_perm.uid, msg_perm.gid, msg perm.mode, and msg qbytesmsg_perm.mode, and msg_qbytes

cmd = IPC_RMID:remove the message queue.

UNIX System Programmingby Yang-Sae MoonPage 30

Page 31: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

msgsnd()msgsnd()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg h>#include <sys/msg.h>

int msgsnd(int msqid, const void *ptr, size_t nbytes, int flag); Returns: 0 if OK, -1 on error

msgsnd() places a message at the end of the queue.

• ptr: pointer that points to a message• ptr: pointer that points to a message

• nbytes: length of message data

• if flag = IPC NOWAIT: IPC NOWAIT is similar to the nonblocking I/O flag for • if flag = IPC_NOWAIT: IPC_NOWAIT is similar to the nonblocking I/O flag for file I/O.

Structure of messages

struct mymesg {long mtype; /* positive message type */char mtext[512]; /* message data, of length nbytes */

UNIX System Programmingby Yang-Sae MoonPage 31

char mtext[512]; / message data, of length nbytes /};

Page 32: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

msgrcv()msgrcv()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h>#include <sys/msg.h>

int msgrcv(int msqid, void *ptr, size_t nbytes, long type, int flag); Returns: data size in message if OK, -1 on error

msgrcv() retrieves a message from a queue.

type 0: the first message on the queue is returnedtype == 0: the first message on the queue is returned

type > 0: the first message on the queue whose message type equals type is returnedtype is returned

type < 0: the first message on the queue whose message type is the lowest value less than or equal to the absolute value of type is q ypreturned

flag may be given by IPC_NOWAIT

UNIX System Programmingby Yang-Sae MoonPage 32

Page 33: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: sender.c receiver.c (1/4): sender.c receiver.c (1/4)APUE (Interprocess Communication

#include <stdio.h> // sender.c#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

#define DEFINED_KEY 0x10101010

main(int argc, char **argv){

i t idint msg_qid;struct {

long mtype;char content[256];

} msg;g

fprintf(stdout, "=========SENDER==========\n");

if((msg_qid = msgget(DEFINED_KEY, IPC_CREAT | 0666)) < 0) {perror("msgget: "); exit(-1);perror( msgget: ); exit( 1);

}

msg.mtype = 1;while(1) {

t( t t 0 0 256)memset(msg.content, 0x0, 256);gets(msg.content);if(msgsnd(msg_qid, &msg, sizeof(msg.content), 0) < 0) {

perror("msgsnd: "); exit(-1);}

UNIX System Programmingby Yang-Sae MoonPage 33

}}

Page 34: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: sender.c receiver.c (2/4): sender.c receiver.c (2/4)APUE (Interprocess Communication

#include <stdio.h> // receiver.c#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>

#define DEFINED_KEY 0x10101010

main(int argc, char **argv){

i t idint msg_qid;struct {

long mtype;char content[256];

} msg;g

fprintf(stdout, "=========RECEIVER==========\n");

if((msg_qid = msgget(DEFINED_KEY, IPC_CREAT | 0666)) < 0) {perror("msgget: "); exit(-1);perror( msgget: ); exit( 1);

}

while(1) {memset(msg.content, 0x0, 256);if( ( id 256 0 0) < 0) {if(msgrcv(msg_qid, &msg, 256, 0, 0) < 0) {

perror("msgrcv: "); exit(-1);}puts(msg.content);

}

UNIX System Programmingby Yang-Sae MoonPage 34

}

Page 35: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: sender.c receiver.c (3/4): sender.c receiver.c (3/4)APUE (Interprocess Communication

실행 결과

UNIX System Programmingby Yang-Sae MoonPage 35

Page 36: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: sender.c receiver.c (4/4): sender.c receiver.c (4/4)APUE (Interprocess Communication

Message Queue 확인

UNIX System Programmingby Yang-Sae MoonPage 36

Page 37: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Shared MemoryShared MemoryAPUE (Interprocess Communication

Allows multiple processes to share a region of memory

• Fastest form of IPC: no need of data copying between client & server py g

If a shared memory segment is attached

• It become a part of a process data space, and shared among multiple processes

Readers and writers may use semaphore to

• synchronize access to a shared memory segment

UNIX System Programmingby Yang-Sae MoonPage 37

Page 38: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Shared Memory Segment StructureShared Memory Segment StructureAPUE (Interprocess Communication

Each shared memory has a structure

struct shmid ds { _ {struct ipc_perm shm_perm; struct anon_map *shm_amp; /* pointer in kernel */int shm_segsz; /* size of segment in bytes */ h t h lk t /* # f ti t i b i l k d */ushort shm_lkcnt; /* # of times segment is being locked */

pid_t shm_lpid; /* pid of last shmop() */ pid_t shm_cpid; /* pid of creator */ ulong shm nattch; /* # of current attaches */ g _ ; / # /ulong shm_cnattch; /* used only for shminfo() */ time_t shm_atime; /* last-attach time */ time_t shm_dtime; /* last-detach time */ ti t h ti /* l t h ti */time_t shm_ctime; /* last-change time */ };

We can get the structure using shmctl() function.

Actually, however, we don’t need to know the structure in detail.

UNIX System Programmingby Yang-Sae MoonPage 38

Page 39: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

shmget()shmget()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm h>#include <sys/shm.h>

int shmget(key_t key, int size, int flag); Returns: shared memory ID if OK, -1 on error

Obtain a shared memory identifier

size: is the size of the shared memory segment

flag: ipc_perm.mode

Example

shmId = shmget(key, size, PERM|IPC_CREAT|IPC_EXCL|0666);

UNIX System Programmingby Yang-Sae MoonPage 39

Page 40: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

shmctl()shmctl()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm h>#include <sys/shm.h>

int shmctl(int shmid, int cmd, struct shmid_ds *buf);Returns: 0 if OK, -1 on error

Performs various shared memory operations

cmd = IPC_STAT:fetch the shmid_ds structure into buf

cmd = IPC_SET:set the following three fields from buf: shm_perm.uid, shm_perm.gid, and shm perm.modeand shm_perm.mode

cmd = IPC_RMID:remove the shared memory segment set from the system

UNIX System Programmingby Yang-Sae MoonPage 40

Page 41: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

shmat()shmat()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm h>#include <sys/shm.h>

void *shmat (int shmid, void *addr, int flag); Returns: pointer to shared memory segment if OK, -1 on error

Attached a shared memory to an address

flag = SHM_RDONLY: the segment is read-only

addr==0: at the first address selected by the kernel (recommended!)addr 0: at the first address selected by the kernel (recommended!)

addr!=0: at the address given by addr

UNIX System Programmingby Yang-Sae MoonPage 41

Page 42: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Memory LayoutMemory LayoutAPUE (Interprocess Communication

high address command-line arguments

stack

and environment variables0xf7fffb2c

shared memory0xf77e86a00xf77d0000

shared memory of 100,000 bytes

uninitialized data

heap 0x0003d2c80x00024c28

malloc of 100,000 bytes

0x0003d2c8uninitialized data(bss)

initialized data

0x0003d2c80x00024c28 array[] of 40,000 bytes

textlow address

UNIX System Programmingby Yang-Sae MoonPage 42

Page 43: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

shmdt()shmdt()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm h>#include <sys/shm.h>

void shmdt (void *addr); Returns: 0 if OK, -1 on error

Detach a shared memory segment

UNIX System Programmingby Yang-Sae MoonPage 43

Page 44: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

예제예제: tshm.c (1/2): tshm.c (1/2)APUE (Interprocess Communication

#include <sys/types.h> // tshm.c#include <sys/ipc.h>#include <sys/shm.h>

#define ARRAY SIZE 100000#define ARRAY_SIZE 100000#define MALLOC_SIZE 100000#define SHM_SIZE 100000

err_sys(char *p) { perror(p); exit(-1); }

char array[ARRAY_SIZE]; /* uninitialized data = bss */

int main(void) {int shmid; char *ptr, *shmptr;

printf("array[] from %x to %x\n", &array[0], &array[ARRAY_SIZE]);printf("stack around %x\n", &shmid);

if ((ptr = malloc(MALLOC_SIZE)) == NULL) err_sys("malloc error");_ _printf("malloced from %x to %x\n", ptr, ptr+MALLOC_SIZE);

if ((shmid = shmget(0x01010101, SHM_SIZE, IPC_CREAT | 0666)) < 0)err_sys("shmget error");

if ((shmptr = shmat(shmid, 0, 0)) == (void *) -1) err_sys("shmat error");printf("shared memory attached from %x to %x\n", shmptr, shmptr+SHM_SIZE);

// if (shmctl(shmid, IPC_RMID, 0) < 0) err_sys("shmctl error");

UNIX System Programmingby Yang-Sae MoonPage 44

exit(0);}

Page 45: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

APUE (Interprocess Communication예제예제: tshm.c (2/2): tshm.c (2/2)

실행 결과

UNIX System Programmingby Yang-Sae MoonPage 45

Page 46: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

SemaphoresSemaphoresAPUE (Interprocess Communication

A counter to provide access to shared data object for multiple processes (복수의 프로세스가 데이터를 공유하는데 사용하는 카운터)

To obtain a shared resource:

• 1. Test semaphore that controls the resource (확인하여)

• 2. If value > 0, value--, grant use (양수이면, 감소시키고 사용하고)

• 3. If value == 0, sleep until value > 0 (0이면 기다림)

• 4. Release resource, value ++ (다 쓴 후에는 다시 양수로 만듦)

Step 1, 2 must be an atomic operation

UNIX System Programmingby Yang-Sae MoonPage 46

Page 47: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

Semaphore StructureSemaphore StructureAPUE (Interprocess Communication

Each semaphore has a structure

struct semid ds { _ {struct ipc_perm sem_perm;struct sem *sem_base; /*ptr to first semaphore in set */ ushort sem_nsems; /* # of semaphors in set */ ti t ti /* l t () ti */time_t sem_otime; /* last-semop() time */ time_t sem_ctime; /* last-change time */

};

struct sem { ushort semval; /* semaphore value, always >= 0 */ pid_t sempid; /* pid for last operation */ h t t /* # iti l > l */ushort semncnt; /* # processes awaiting semval > currval */

ushort semzcnt; /* # processes awaiting semval = 0 */ };

We can get the structure using semctl() function.

Actually, however, we don’t need to know the structure in detail.

UNIX System Programmingby Yang-Sae MoonPage 47

Page 48: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

semget()semget()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem h>#include <sys/sem.h>

int semget(key_t key, int nsems, int flag); Returns: semaphore ID if OK, -1 on error

Obtain a semaphore ID

nsems: sem_nsens (# of semaphores in set)

flag: ipc_perm.mode

UNIX System Programmingby Yang-Sae MoonPage 48

Page 49: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

semctl()semctl()APUE (Interprocess Communication

#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem h>#include <sys/sem.h>

int semctl(int semid, int semnum, int cmd, union semun arg);

union semun {int val; /* for SETVAL */struct semid_ds *buf; /* for IPC_START and IPC_SET */ushort *array; /* for GETALL and SETALL */ushort array; / for GETALL and SETALL /

};

T h l f h b k d l l d To use semaphore, please refer to the textbook and manuals related semaphore.

UNIX System Programmingby Yang-Sae MoonPage 49

Page 50: 16. APUE(Interprocess Communication)cs.kangwon.ac.kr/~ysmoon/courses/2009_2/us/16.pdf · Two file descriptors are returned through the fd argument • fd[0]: can be used to read from

ipcs, ipcrmipcs, ipcrmAPUE (Interprocess Communication

ipcs:System V IPC의 상태를 확인하는 명령어

• $ ipcs // IPC 정보를 확인 (q, m, s 모두)(q, , )

• $ ipcs –q ($ ipcs –qa) // Message Queue 정보를 확인

• $ ipcs –m ($ ipcs –ma) // Shared Memory 정보를 확인

• $ ipcs –s ($ ipcs –sa) // Semaphore 정보를 확인

ipcrm: 정의된(생성된)IPC를 삭제함

• $ ipcrm –q id // Message Queue를 삭제

$ i id // Sh d M 를 삭제• $ ipcrm –m id // Shared Memory를 삭제

• $ ipcrm –s id // Semaphore를 삭제

UNIX System Programmingby Yang-Sae MoonPage 50