Embedded System Design Lecture 9 Jaeyong Chung Robust Systems Laboratory Incheon National University
Inter-process Commnucation (IPC) Chung EPC6071 2
Inter-process Commnucation (IPC) A set of methods for the exchange of data among processes. Processes may be running on one or more computers connected by a network. Mechanism for processes to communicate and to synchronize their actions IPC methods are divided into methods for message passing (like SMS), synchronization, shared memory (like boards on web), remote procedure calls Main IPC methods File, Signal, Socket, Message Queue, Pipe, Semaphore, Shard memory Chung EPC6071 3
Message Passing Message system processes communicate with each other without resorting to shared variables. It can also provides synchronization Two operations read, write If P and Q wish to communicate, they need to: establish a communication link between them exchange messages via send/receive Message passing may be either blocking or nonblocking Blocking is considered synchronous Blocking send has the sender block until the message is received Blocking receive has the receiver block until a message is available Chung EPC6071 4
Blocking/Non-blocking Message passing may be either blocking or nonblocking Blocking is considered synchronous Blocking send has the sender block until the message is received Blocking receive has the receiver block until a message is available Non-blocking is considered asynchronous Non-blocking send has the sender send the message and continue Non-blocking receive has the receiver receive a valid message or null Chung EPC6071 5
More on File IO read Function Returns: number of bytes read if OK, 0 if end of file, - 1 on error #include <unistd.h> ssize_t read(int filedes, void *buff, size_t nbytes); Process/thread blocks until some data is read Note that 0 indicates end of file Chung EPC6071 6
More on File IO write Function #include <unistd.h> ssize_t write(int filedes, const void *buff, size_t nbytes); Returns: number of bytes written if OK, -1 on error Process/thread blocks until some data is written Chung EPC6071 7
(IPC Method 1) Pipe IPC method based on message passing A two-way data stream that is read character by character. For processes in the same machine Use read() and write() system calls Once communication links are set up, reading/writing data is the same as doing it to a file Every process has three default pipes Stdin (filedesc: 0), stdout (filedes: 1), stderr (filedesc:2 ) By default, these pipes are connected to terminal program Chung EPC6071 8
(IPC Method 1) Pipe Redirect stdout to a file./program > output.txt Redirect stderr to a file./program 2> errors.txt Redirect stderr to stdout./program 2>&1 Chung EPC6071 9
(IPC Method 1) Pipe Redirect stdout to stdin of another program./program1./program2 Chain of programs./program1./program2./program3 Chung EPC6071 10
Activity Create a file that contains all file names in CWD Create a file that contains the list of current processes owned by chung A program (./a.out) displays a lot of messages during the execution. Kick off the program so that it displays messages contatining WARNING string Chung EPC6071 11
(IPC Method 2) Socket Programming IPC method based on message passing A two-way data stream that is read character by character. For processes in different machines Use read() and write() system calls Once communication links are set up, reading/writing data is the same as doing it to a file Chung EPC6071 12
(IPC Method 2) Socket Programming int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); } exit(0); portno = atoi(argv[2]); sockfd = socket(af_inet, SOCK_STREAM, 0); if (sockfd < 0) error("error opening socket"); server = gethostbyname(argv[1]); if (server == NULL) { } fprintf(stderr,"error, no such host\n"); exit(0); serv_addr.sin_family = AF_INET; } bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("error connecting"); printf("please enter the message: "); bzero(buffer,256); fgets(buffer,255,stdin); n = write(sockfd,buffer,strlen(buffer)); if (n < 0) error("error writing to socket"); bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) error("error reading from socket"); printf("%s\n",buffer); return 0; Chung EPC6071 13
Activity Write a function that must read a number of bytes desired from a socket, a pipe, a file, or so on. It blocks until the number of bytes is read Chung EPC6071 14
(IPC Method 3) Signal A limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems A signal is an asynchronous notification sent to a process in order to notify it of an event that occurred When a signal is sent, the operating system interrupts the target process s normal flow of execution to deliver the signal. If the process has previously registered a signal handler, that routine is executed Analogous to an interrupt, but it is entirely a software creation kill() system calls $ kill 9 pid Chung EPC6071 15
(IPC Method 4) Shared Memory Processes have some memory in common Implemented by page sharing Synchronization using shared memory can be problematic Polling Race condition: The output is dependent on the sequence or timing of other uncontrollable events. [Silberschartz et al] Chung EPC6071 16
Blocking I/O Issues Case 1) I am writing a shooting-game program. I need to update positions of enemies and read inputs from keyboard at the same time. But reading from keyboard blocks the process Case 2) I am writing a chatting server. What happens if the server process waits for a client s message and it is not sent for a while? Solution 1: Non-blocking I/O Solution 2: Blocking I/O + Concurrent Programming Chung EPC6071 17
Non-blocking I/O Make read() return immediately If you have your own device driver, change your device in such way In general, Issues: int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags O_NONBLOCK); Busy-waiting: waste CPU time To relieve this, add sleep(), but this hurts response time Fairness Complexity: Applications play some of OS es roles Chung EPC6071 18
Concurrent Programming A CPU executes a program Multiple CPUs can execute a program in parallel This can be emulated in a single CPU system by timesharing May be considered as CPU virtualization A virtual CPU has its own PC value, register values, etc Multiple threads/processes can execute a program in parallel A thread is specified by PC value, register values, etc Chung EPC6071 19
Concurrent Programming Multi-processes (heavy) Each process has its own virtual address space Variables are not shared unless using shared memory IPC may complicate programming Multi-threading (light) Each thread share one virtual address space Global variables are shared To allow threads to access the same variables, synchronization through mutex is needed which complicates programming Race conditions are hard to debug Chung EPC6071 20
Activity Write an example of the output when the following program is executed by two threads and two processes int i = 0; void test() { } while(1) { } printf( %d\n, i++); 2 processes 2 threads Chung EPC6071 21
Activity Write an example of the output when the following program is executed by two threads ADR R2, i LDR R1, [R2] ADD R1, R1, #1 STR R1, [R2] 2 threads Chung EPC6071 22
Race Condition in Shared Memory Problem when two CPUs try to write the same location: CPU 1 reads flag and sees 0. CPU 2 reads flag and sees 0. CPU 1 sets flag to one and writes location. CPU 2 sets flag to one and overwrites location. Chung EPC6071 23
Atomic test-and-set Problem can be solved with an atomic test-and-set: single bus operation reads memory location, tests it, writes it. ARM test-and-set provided by SWP: ADR r0,semaphore LDR r1,#1 GETFLAG SWP r1,r1,[r0] BNZ GETFLAG Chung EPC6071 24
Critical Regions Critical region/section: section of code that cannot be interrupted by another process. Critical region is created by: Mutex in multi-threading Semaphores in multi-processing Chung EPC6071 25
Mutex in pthread #include <pthread.h> pthread_mutex_t count_mutex; long long count; Void increment_count() { pthread_mutex_lock(&count_mutex); // critical section begin count = count + 1; pthread_mutex_unlock(&count_mutex); // critical section end } long long get_count() { long long c; pthread_mutex_lock(&count_mutex); // critical section begin c = count; pthread_mutex_unlock(&count_mutex); // critical section end return (c); } Chung EPC6071 26
Semaphores in Linux void count() { sem_t *my_semaphore; my_semaphore = sem_open( /sem1, oflags); sem_wait(my_semaphore); // P // Do something; // critical section sem_post(my_semaphore); // V sem_close(my_semaphore); } Chung EPC6071 27