Date post: | 14-Apr-2018 |
Category: |
Documents |
Upload: | carlos-hernan-acero-charana |
View: | 218 times |
Download: | 0 times |
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 1/33
NET-CENTRIC COMPUTING (NC) I
M.Sc. Julio Santisteban Pablo
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 3/33
A socket is defined as an endpoint for
communication.
Socket protocol specific address:
Internet domain (INET) - concatenation of an IP addressand port
UNIX domain - pathnames within the normal filesystem.
The socket 161.25.19.8:1625 refers to port 1625 on
host 161.25.19.8 Communication consists between a pair of sockets.
Sockets
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 4/33
Remote Procedure Calls (RPC)
Remote procedure call abstracts procedure callsbetween processes on networked systems.
Stubs – client-side proxy for the actual procedure
on the server. The client-side stub locates the server and
marshalls the parameters.
The server-side stub receives this message,unpacks the marshalled parameters, and performsthe procedure on the server.
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 5/33
Pipes and FIFOs
Pipe: a circular buffer of fixed size written by oneprocess and read by another
int pipe(int fildes[2]) : creates a pipe and returns twofile descriptors, fildes [0] and fildes [1] for reading and
writing OS enforces mutual exclusion: only one process at a
time can access the pipe.
accessed by a file descriptor, like an ordinary file
processes sharing the pipe must have same parent incommon and are unaware of each other's existence
Unlike pipes, a FIFO has a name associated with it,allowing unrelated processes to access a single FIFO
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 6/33
UNIX Pipes
Unidirectional, FIFO, unstructured datastream
Fixed maximum size Simple flow control
pipe() system call creates two filedescriptors. Why?
Implemented using filesystem, sockets or STREAMS (bidirectional pipe).
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 7/33
Named Pipes
Lives in the filesystem - that is, a file is createdof type S_IFIFO (use mknod() or mkfifo())
may be accessed by unrelated processes
persistent
less secure than regular Pipes. Why?
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 8/33
Pipe Examplemain()
{
int n;
int pipefd[2];
char buff[100];
if (pipe(pipefd) < 0) // create a pipe
perror("pipe error");
printf(“read fd = %d, writefd = %d\n”, pipefd[0], pipefd[1]);
if (write(pipefd[1], “hello world\n”, 12) !=12) // write to pipe
perror("write error");
if ((n=read(pipefd[0], buff, sizeof(buff))) <=0) //read from pipe
perror("read error");
write(1, buff, n ); /* write to stdout */
close(pipefd[0]);close(pipefd[1]);
exit(0);
}
Result:
read fd = 3, writefd = 4
hello world
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 9/33
Messages Processes read and write messages to arbitrary message queues (like
mailboxes)
System calls:
int msgget (key_t key, int flag) : Creates or accesses a messagequeue, returns message queue identifier
int msgsnd(int msqid, const void *msgp, size_t msgsz, int flag) : Puts
a message in the queue int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtype, int
msgflg) : Receives a message and stores it to msgp
msgtype: Messages can be typed and each type defines acommunication channel
int msgctl(int msqid, int cmd, struct msqid_ds *buf) : provides a
variety of control operations on a message queue (e.g. remove) Process is blocked when:
trying to read from an empty queue
trying to send to a full queue
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 10/33
Messages example/* Send and receive messages within a process */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define BUFFSIZE 128
#define PERMS 0666
#define KEY ((key_t) 7777)
main()
{
int i, msqid;
struct {
long m_type;
char m_text[BUFFSIZE];
} msgbuffs, msgbuffr;
if ( (msqid = msgget(KEY, PERMS | IPC_CREAT)) < 0)
perror("msgget error");
msgbuffs.m_type = 1L;
strcpy(msgbuffs.m_text,"a REALLY boring message");
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 11/33
if (msgsnd(msqid, &msgbuffs, BUFFSIZE, 0) < 0)perror("msgsnd error");
printf("the message sent is: %s \n", msgbuffs.m_text);
if (msgrcv(msqid, &msgbuffr, BUFFSIZE, 0L, 0) != BUFFSIZE)
perror("msgrcv error");
printf("the message received is: %s \n", msgbuffr.m_text);
// remove msg
if (msgctl(msqid, IPC_RMID, (struct msqid_ds *) 0) < 0)
perror("IPC_RMID error");
exit(0);
}
RESULT:
the message sent is: a REALLY boring message
the message received is: a REALLY boring message
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 12/33
Shared Memory Processes can share the same segment of memory
directly when it is mapped into the address space of eachsharing process
Faster communication
System calls: int shmget(key_t key, size_t size, int shmflg) : creates a
new region of shared memory or returns an existing one void *shmat(int shmid, const void *shmaddr, int shmflg)
: attaches a shared memory region to the virtualaddress space of the process
int shmdt(char *shmaddr): detaches a shared region Mutual exclusion must be provided by processes using the
shared memory
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 14/33
Shared Memory (continued)
More difficult if processes inherently haveindependent address spaces E.g., Unix, Linux, Windows
Special mechanisms to share a portion of virtualmemory E.g., shmget(), shmctl() in Unix
Memory mapped files in Windows XP/2000, Apollo DOMAIN,etc.
Very, very hard to program! Need critical section management among processes
Pointers are an issue
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 15/33
Shared Memory example// IPC communication between a child and a parent process using// shared memory : the parent puts messages into the shared memory
// the child reads the shared memory and prints the messages
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHMSIZE 15 // maximum number of bytes in a message
#define MESGNUM 2 //number of messages
void cleanup (int shm_id, char *addr); // cleanup procedure
int shm_id; // ID of shared memory
int main (int argc, char *argv[])
{
char message [SHMSIZE]; // the message to send/receive
int i;
int number_of_messages; // number to be sent
int nbytes; // number of bytes in a message
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 16/33
int number_of_messages; // number to be sentint nbytes; // number of bytes in a message
int status;
char *addr = (char *) malloc (SHMSIZE * sizeof (char));
number_of_messages = MESGNUM;
nbytes = SHMSIZE;
// set up shared memory segment using PID as the key
if ((shm_id = shmget ((key_t) getpid(), SHMSIZE, 0666 | IPC_CREAT)) == -1 ){
printf ("Error in shared memory region setup.\n");
exit (2);
} // if shared memory get failed
// attach the shared memory segment
addr = (char *) shmat (shm_id, (char *) 0, 0);
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 17/33
if (fork ()) { // true if in parent process
// create message of required length
for (i=0; i < nbytes; i++)
message [i] = i % 26 + 'a';
message [nbytes] = '\0';
// send message using the shared memory segment
for (i = 0; i < number_of_messages; i++) {
if (memcpy (addr, message, nbytes+1) == NULL) {
puts ("Error in memory copy");
cleanup (shm_id, addr);
exit (3);
} // end if error in memory copy} // end for as many messages as requested
wait (&status); // wait for child to return
// get the message sent by the child
strcpy (message, addr);printf ("Parent - message from child: \n %s\n", message);
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 18/33
strcpy (message, addr);
printf ("Parent - message from child: \n %s\n", message);
cleanup (shm_id, addr);
exit(0);
} // end parent process
// in child process
puts ("Child - messages from parent:");
for (i = 0; i < number_of_messages; i++) {
if (memcpy (message, addr, nbytes+1) == NULL) {
puts ("Error in memcpy");
cleanup (shm_id, addr);
exit (5);
} // end if error in shared memory get
else
puts (message);
} // end for each message sent
strcpy (addr, "I have received your messages!");
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 19/33
exit (0);
} // end main program
// remove shared memory segment
void cleanup (int shm_id, char *addr)
{
shmdt (addr);
shmctl (shm_id, IPC_RMID, 0);
} // end cleanup function
RESULT:
Child - messages from parent:
abcdefghijklmno
abcdefghijklmno
Parent - message from child:
I have received your messages!
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 20/33
Semaphores A semaphore is a non-negative integer
count and is generally used to coordinateaccess to resources
System calls: int sema_init(sema_t *sp, unsigned int count, int type, void
* arg): Initialize semaphores pointed to by sp to count. type can assign several different types of behavior to asemaphore
int sema_destroy(sema_t *sp); destroys any state relatedto the semaphore pointed to by sp. The semaphore storagespace is not released.
int sema_wait(sema_t *sp); blocks the calling thread untilthe semaphore count pointed to by sp is greater than zero,and then it atomically decrements the count.
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 21/33
Semaphores int sema_trywait(sema_t *sp); atomically decrements the
semaphore count pointed to by sp, if the count is greater thanzero; otherwise, it returns an error.
int sema_post(sema_t *sp); atomically increments thesemaphore count pointed to by sp. If there are any threadsblocked on the semaphore,one will be unblocked.
Example: The customer waiting-line in a bankis analogous to the synchronization scheme of
a semaphore using sema_wait() andsema_trywait():
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 23/33
Beyond Semaphores
Semaphores can help solve many traditionalsynchronization problems, e.i. Sharememory BUT:
Have no direct relationship to the data beingcontrolled
Difficult to use correctly; easily misusedGlobal variables
Proper usage requires superhuman attention todetail
Another approach – use programminglanguage support
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 24/33
Semaphores example#include <errno.h>#define TELLERS 10
sema_t tellers; /* semaphore */
int banking_hours(), deposit_withdrawal;
void *customer(), do_business(), skip_banking_today();
...
sema_init(&tellers, TELLERS, USYNC_THREAD, NULL);
/* 10 tellers available */
while(banking_hours())
pthread_create(NULL, NULL, customer, deposit_withdrawal);
...
void * customer(int deposit_withdrawal)
{
int this_customer, in_a_hurry = 50;
this_customer = rand() % 100;
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 25/33
if (this_customer == in_a_hurry) {if (sema_trywait(&tellers) != 0)
if (errno == EAGAIN) { /* no teller available */
skip_banking_today(this_customer);
return;
} /* else go immediately to available teller anddecrement tellers */
}
else
sema_wait(&tellers); /* wait for next teller, thenproceed, and decrement tellers */
do_business(deposit_withdrawal);
sema_post(&tellers); /* increment tellers;
this_customer's teller
is now available */
}
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 26/33
Signals
Software mechanism that allows one process tonotify another that some event has occurred.
Each signal is represented by a numeric value.
Ex: 02, SIGINT: to interrupt a process
09, SIGKILL: to terminate a process
Each signal is maintained as a single bit in the
process table entry of the receiving process: thebit is set when the corresponding signal arrives
A signal is processed as soon as the processruns in user mode
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 27/33
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD
18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN
22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO
30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1
36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5
40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9
44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-1352) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5
60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1
64) SIGRTMAX
Signals
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 28/33
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
// Define the function to be called when
ctrl-c (SIGINT) signal is sent toprocess
void signal_callback_handler(int signum){
printf("Caught signal %d\n",signum);
// Cleanup and close up stuff here
// Terminate program
exit(signum);
}
int main(){
// Register signal and signal handler
signal(SIGINT, signal_callback_handler);
while(1) {
printf("Program processing stuff here.\n");
sleep(1);
}
return EXIT_SUCCESS;
}
Signals
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 29/33
Each of these flags is enabled by supplying itto stty and disabled by supplying it to stty with
the –
character in front of it. Thus, to disablehardware handshaking on the ttyS0 device,you would use:
$ stty -crtscts -F /dev/ttyS0
Serial port linux
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 30/33
crtsdts Enable/Disable hardware handshaking.ixon Enable/Disable XON/XOFF flow control.
clocal Enable/Disable modem control signals such as DTR/DTS and DCD.This is necessary if you are using a "three wire" serial cable because itdoes not supply these signals.
cs5 cs6 cs7 cs8 Set number of data bits to 5, 6, 7, or 8, respectively.
parodd Enable odd parity. Disabling this flag enables even parity.
parenb Enable parity checking. When this flag is negated, no parity is used.
cstopb Enable use of two stop bits per character. When this flag is negated,one stop bit per character is used.
echo Enable/Disable echoing of received characters back to sender.
The next example combines some of these flags and sets the ttyS0 device to19,200 bps, 8 data bits, no parity, and hardware handshaking with echodisabled:
$ stty 19200 cs8 -parenb crtscts -echo -F /dev/ttyS0
Serial port linux
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 31/33
In Linux all devices have a file in /dev directory, so the communication with thesedevices is very simple, just need to open
necessary file, and make read and writeoperations upon them.
Serial port linux
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 32/33
#include <stdio.h> #include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h> int fd1;
int fd2;
char *buff,*buffer,*bufptr;
int wr,rd,nbytes,tries;
int main(){ return 0;
}
//Next step, we connect to devicethrough associated file and check theconnection:
fd1=open(“/dev/ttyS0″, O_RDWR |O_NOCTTY | O_NDELAY);
if (fd1 == -1 ){
perror (“open_port: Unable to open /dev/ttyS0 – “);
}
Else {
fcntl(fd1, F_SETFL,0);
printf (“Port 1 has been sucessfullyopened and %d is the filedescription\n”,fd1);
}
Serial port linux
7/27/2019 CCRI IPC
http://slidepdf.com/reader/full/ccri-ipc 33/33
Where, “/dev/ttyS0” is associated with COM1 port.
With following code we send to device some bits:
wr =write(fd1,”ATZ \r”,4);
And for reading response from device:
rd=read(fd1,buff,10);
printf (“Bytes sent are %d \n”,rd);
At the end, close the connection:close(fd1);
Serial port linux