You are on page 1of 44

AES Lab manual

REVA ITM

AES LAB Subject code : 10EC118 IA Marks : 25

Lab Experiments: I. Advanced Embedded Systems


0 1. Use any EDA (Electronic Design Automation) tool to learn the Embedded Hardware Design and for PCB design. 1 2. Familiarize the different entities for the circuit diagram design. 2 3. Familiarize with the layout design tool, building blocks, component placement, routings, design rule checking etc.

06 ECL 57

AES Lab manual

REVA ITM

Introduction :
Electronic design automation (EDA or ECAD) is a category of software tools for designing electronic systems such as printed circuit boards and integrated circuits. The tools work together in a design flow that chip designers use to design and analyze entire semiconductor chips. History Early days Before EDA, integrated circuits were designed by hand, and manually laid out. Some advanced shops used geometric software to generate the tapes for the Gerber photoplotter, but even those copied digital recordings of mechanically-drawn components. The process was fundamentally graphic, with the translation from electronics to graphics done manually. The best known company from this era was Calma, whose GDSII format survives. By the mid-70s, developers started to automate the design, and not just the drafting. The first placement and routing (Place and route) tools were developed. The proceedings of the Design Automation Conference cover much of this era. The next era began about the time of the publication of "Introduction to VLSI Systems" by Carver Mead and Lynn Conway in 1980. This ground breaking text advocated chip design with programming languages that compiled to silicon. The immediate result was a considerable increase in the complexity of the chips that could be designed, with improved access to design verification tools that used logic simulation. Often the chips were easier to lay out and more likely to function correctly, since their designs could be simulated more thoroughly prior to construction. Although the languages and tools have evolved, this general approach of specifying the desired behavior in a textual programming language and letting the tools derive the detailed physical design remains the basis of digital IC design today. The earliest EDA tools were produced academically. One of the most famous was the "Berkeley VLSI Tools Tarball", a set of UNIX utilities used to design early VLSI systems. Still widely used is the Espresso heuristic logic minimizer and Magic. Another crucial development was the formation of MOSIS, a consortium of universities and fabricators that developed an inexpensive way to train student chip designers by producing real integrated circuits. The basic concept was to use reliable, low-cost, relatively low-technology IC processes, and pack a large number of projects per wafer, with just a few copies of each projects' chips. Cooperating fabricators either donated the processed wafers, or sold them at cost, seeing the program as helpful to their own long-term growth.

06 ECL 57

AES Lab manual Birth of commercial EDA

REVA ITM

1981 marks the beginning of EDA as an industry. For many years, the larger electronic companies, such as Hewlett Packard, Tektronix, and Intel, had pursued EDA internally. In 1981, managers and developers spun out of these companies to concentrate on EDA as a business. Daisy Systems, Mentor Graphics, and Valid Logic Systems were all founded around this time, and collectively referred to as DMV. Within a few years there were many companies specializing in EDA, each with a slightly different emphasis. The first trade show for EDA was held at the Design Automation Conference in 1984. In 1986, Verilog, a popular high-level design language, was first introduced as a hardware description language by Gateway Design Automation. In 1987, the U.S. Department of Defense funded creation of VHDL as a specification language. Simulators quickly followed these introductions, permitting direct simulation of chip designs: executable specifications. In a few more years, back-ends were developed to perform logic synthesis.

3D PCB layout Current status Current digital flows are extremely modular (see Integrated circuit design, Design closure, and Design flow (EDA)). The front ends produce standardized design descriptions that compile into invocations of "cells,", without regard to the cell technology. Cells implement logic or other electronic functions using a particular integrated circuit technology. Fabricators generally provide libraries of components for their production processes, with simulation models that fit standard simulation tools. Analog EDA tools are far less modular, since many more functions are required, they interact more strongly, and the components are (in general) less ideal. EDA for electronics has rapidly increased in importance with the continuous scaling of semiconductor technology.[citation needed] Some users are foundry operators, who operate the semiconductor fabrication facilities, or "fabs", and design-service companies who use EDA software to evaluate an incoming design for manufacturing readiness. EDA tools are also used for programming design functionality into FPGAs

06 ECL 57

AES Lab manual

REVA ITM

Many open-source EDA (Electronic Design Automation) tools including Magic, IRSIM, Netgen, PCB, and XCircuit are available and many commercial EDA tools like Cadence, Protel, Zuken, Mentor Graphics,Synopsys etc.,

In this lab Orcad tool from Cadence is used for schematic and PCB design

3 1. Use any EDA (Electronic Design Automation) tool to learn the Embedded Hardware Design and for PCB design. 2

1. Starting a New Schematic Project 06 ECL 57 4

AES Lab manual

REVA ITM

To create a new project, first start OrCAD Capture and click FileNewProject. You will see the following dialog box.

Browse to the sch directory that you created and name the project Elec424Tutorial. You now have an empty project workspace. You should see an empty schematic page and a project window like the following.

06 ECL 57

AES Lab manual

REVA ITM

2.

Creating a Schematic Parts Library

OrCAD allows you to create a library of part symbols for use in schematic entry. These libraries are kept in separate files that are included in the project workspace. This allows you to reuse libraries in other designs. We will know create symbols for all the parts in our design. IMPORTANT NOTE: When you place a part in a design, OrCAD creates a cached copy of the part symbol in the design file. This makes schematic projects portable but can also introduce some problems later in the design cycle. Please resist the temptation to edit parts directly in schematics, as this will make the design out of sync with respect to your library. Always edit symbols in the library
06 ECL 57 6

AES Lab manual

REVA ITM

and then use the Replace Cache and Update Cache commands to change the part in schematics. See the OrCAD help for more information on these commands. First we must add a new library to our design. To do this, click File->New->Library. Your project window will now look like the figure on the left. Right-click the library file and select Save As... Name the file Elec424Tutorial and place it in the lib directory that you created earlier. You are now ready to add parts to your library.

06 ECL 57

AES Lab manual

REVA ITM

Experiment No 1: Draw a Schematic Diagram for CMOS CPU Design using 8 bit 80C51 Microcontroller, 82C82 buffer,51C68 Memory(4bit), clock of 12 MHz, and power supply circuit (using LM123 regulator)
Aim : To draw the circuit schematic of CMOS CPU

Procedure : 1. Open ORCAD Capture CIS tool 2. Open File , New Project, give the name as CMOSCPU 3. Check an empty schematic page and a project window like the following workspace 4. Open Page1 schematic

Place a 80c51 microcontroller part by using Place part

06 ECL 57

AES Lab manual

REVA ITM

6. 7. 8. 9. 10. 11.

Repeat the same step 4 by placing all the components required for the design, resistors(R1 Rn), Capacitors(C1.. Cn), Crystal (X1), Buffer(82c92), reset switch(Sw), etc., Using Place Net and do the circuit connections of all the components net connections Place GND and VCC connections and connect GND and VCC connections of the circuit schematics. Using placing page connectors connect page 1 net to page 2 and page 3 schematics. Check/Run the DRC(Design rules check) of page1 Check for any errors and correct/modify the circuit if any erros.

Repeat Same steps from 4 to 11 for pages 2 and 3 For each Page enter the title block 12 Run Design Rule Check for the entire project, Which gives the following log in the output file as cmoscpu.drc.

******************************************************************************** * * Design Rules Check * ******************************************************************************** Checking for Invalid Pins in Package -------------------------------------------------Checking Schematic: MEMORY -------------------------------------------------Checking Electrical Rules Checking for Invalid References Checking for Duplicate References -------------------------------------------------Checking Schematic: CMOSCPU -------------------------------------------------Checking Electrical Rules Checking for Invalid References Checking for Duplicate References -------------------------------------------------Checking Schematic: POWER -------------------------------------------------Checking Electrical Rules

13 14
06 ECL 57

Check for any errors Create/Run Netlist using .mnl format or .net format
9

AES Lab manual

REVA ITM

15 16

Create/Run Bill of Materials Check the schematics with netlist.

Result : Schematic of CMOS CPU Circuit diagram Attach the schematic of CMOS CPU and the netlist

Experiment 2 : Draw a Circuit Schematic for Full Adder Circuit Aim : To draw the circuit schematic of FULL Adder

Procedure : 1. Open ORCAD Capture CIS tool 2. Open File , New Project, give the name as FULLADD 3. Check an empty schematic page and a project window like the following workspace 4. Open Page1 schematic 5. Draw two Half adder circuit in page 1. 6. Place 74LS 32 OR gate 7. Open Page 2 schematic 8. Place the part/components require for the half adder(74LS08,74LS04,74LS32,74LS08) 9. Connect the net /pin connections of all the components 10.Run Design Rule Check for the entire project. 11. Check for any errors 12.Create/Run Netlist using .mnl format or .net format 13.Check the schematics with netlist.

06 ECL 57

10

AES Lab manual

REVA ITM

06 ECL 57

11

AES Lab manual

REVA ITM

06 ECL 57

12

AES Lab manual

REVA ITM

06 ECL 57

13

AES Lab manual

REVA ITM

06 ECL 57

14

AES Lab manual

REVA ITM

06 ECL 57

15

AES Lab manual

REVA ITM

06 ECL 57

16

AES Lab manual

REVA ITM

06 ECL 57

17

AES Lab manual

REVA ITM

06 ECL 57

18

AES Lab manual

REVA ITM

06 ECL 57

19

AES Lab manual

REVA ITM

06 ECL 57

20

AES Lab manual

REVA ITM

II. Embedded Programming Concepts (RTOS)


Operating System Basics The Operating System acts as a bridge between the user applications/tasks and the underlying system resources through a set of system functionalities and services OS manages the system resources and makes them available to the user applications/tasks on a need basis The primary functions of an Operating system is Make the system convenient to use Organize and manage the system resources efficiently and correctly

User Applications
Kernel Services
Mem Manag ent ory em P roces Ma em s nag ent T e Manag ent im em F S tem Manag ent ile ys em I/O S temMan em ys ag ent

Application Programming Interface (API)

UnderlyingH ardware
Embedded system RTOS

Device Driver Interface

Enables execution of concurrent processes or threads or tasks Provides a mechanism to let the processor run each process as per scheduling and to do context-switch between the various processes (threads or tasks) RTOS sets the rules during execution of application processes to enable finishing of a process within the assigned time interval and with ssigned priority.

06 ECL 57

21

AES Lab manual

REVA ITM

The Kernel The kernel is the core of the operating system It is responsible for managing the system resources and the communication among the hardware and other system services Kernel acts as the abstraction layer between system resources and user applications Kernel contains a set of system libraries and services. For a general purpose OS, the kernel contains different services like Process Management Primary Memory Management File System management I/O System (Device) Management Secondary Storage Management Protection Time management Interrupt Handling

Types of Operating Systems Depending on the type of kernel and kernel services, purpose and type of computing systems where the OS is deployed and the responsiveness to applications, Operating Systems are classified into General Purpose Operating System (GPOS) Operating Systems, which are deployed in general computing systems The kernel is more generalized and contains all the required services to execute generic applications Need not be deterministic in execution behavior May inject random delays into application software and thus cause slow responsiveness of an application at unexpected times Usually deployed in computing systems where deterministic behavior is not an important criterion Personal Computer/Desktop system is a typical example for a system where GPOSs are deployed. Windows XP/MS-DOS etc are examples of General Purpose Operating System Real Time Purpose Operating System (RTOS) Operating Systems, which are deployed in embedded systems demanding real-time response Deterministic in execution behavior. Consumes only known amount of time for kernel applications Implements scheduling policies for executing the highest priority task/application always Implements policies and rules concerning time-critical allocation of a systems resources Windows CE, QNX, VxWorks MicroC/OS-II etc are examples of Real Time Operating Systems (RTOS) 22

06 ECL 57

AES Lab manual

REVA ITM

Features of RTOS a. b. c. d. e. f. g. h. i. j. k. l. Multitasking with preemptive task scheduling Round Robin and Time-Sliced scheduling within same priority level Support for static and dynamically created tasks Fixed or dynamically changeable task priorities Intertask communication and synchronization via semaphores, messages, and queues Efficient timer management Timeouts on many services Management of memory Resource management Fast context switch Small RAM and ROM requirements Standard programmer interface on all processors Highly flexible configuration to permit custom fit to the application

Hard Real-time System A Real Time Operating Systems which strictly adheres to the timing constraints for a task A Hard Real Time system must meet the deadlines for a task without any slippage Missing any deadline may produce catastrophic results for Hard Real Time Systems, including permanent data lose and irrecoverable damages to the system/users Emphasize on the principle A late answer is a wrong answer Air bag control systems and Anti-lock Brake Systems (ABS) of vehicles are typical examples of Hard Real Time Systems As a rule of thumb, Hard Real Time Systems does not implement the virtual memory model for handling the memory. This eliminates the delay in swapping in and out the code corresponding to the task to and from the primary memory The presence of Human in the loop (HITL) for tasks introduces un-expected delays in the task execution. Most of the Hard Real Time Systems are automatic and does not contain a human in the loop Soft Real-time System Real Time Operating Systems that does not guarantee meeting deadlines, but, offer the best effort to meet the deadline Missing deadlines for tasks are acceptable if the frequency of deadline missing is within the compliance limit of the Quality of Service (QoS) A Soft Real Time system emphasizes on the principle A late answer is an acceptable answer, but it could have done bit faster Soft Real Time systems most often have a human in the loop (HITL) Automatic Teller Machine (ATM) is a typical example of Soft Real Time System. If the ATM takes a few seconds more than the ideal operation time, nothing fatal happens. 23

06 ECL 57

AES Lab manual

REVA ITM

An audio video play back system is another example of Soft Real Time system. No potential damage arises if a sample comes late by fraction of a second, for play back

Tasks, Processes & Threads In the Operating System context, a task is defined as the program in execution and the related information maintained by the Operating system for the program Task is also known as Job in the operating system context A program or part of it in execution is also called a Process The terms Task, job and Process refer to the same entity in the Operating System context and most often they are used interchangeably A process requires various system resources like CPU for executing the process, memory for storing the code corresponding to the process and associated variables, I/O devices for information exchange etc Process States & State Transition The creation of a process to its termination is not a single step operation The process traverses through a series of states during its transition from the newly created state to the terminated state The cycle through which a process changes its state from newly created to execution completed is known as Process Life Cycle. The various states through which a process traverses through during a Process Life Cycle indicates the current status of the process with respect to time and also provides information on what it is allowed to do next

C a d re te

In p din m m ry ce te to e o

In rru te o te p d r

e Shar

n l et io om p e Ac quir ed I/ O C sour c e
d R

Ray ed S h d le fo c eu d r

E c tio xe u n

B cke lo d
W ai t Waiti i ng fo ng f or I r s ha / red R O esou

P em te re p d R n in un g

rce

E cu n C m le n xe tio o p tio

06 ECL 57

C m le d o p te

24

AES Lab manual

REVA ITM

Threads A thread is the primitive that can execute code A thread is a single sequential flow of control within a process Thread is also known as lightweight process A process can have many threads of execution Different threads, which are part of a process, share the same address space; meaning they share the data memory, code memory and heap memory area Threads maintain their own thread status (CPU register values), Program Counter (PC) and stack

The Concept of multithreading Use of multiple threads to execute a process brings the following advantage. Better memory utilization. Multiple threads of the same process share the address space for data memory. This also reduces the complexity of inter thread communication since variables can be shared across the threads. Since the process is split into different threads, when one thread enters a wait state, the CPU can be utilized by other threads of the process that do not require the event, which the other thread is waiting, for processing. This speeds up the execution of the process. 06 ECL 57 25

AES Lab manual Efficient CPU utilization. The CPU is engaged all time.

REVA ITM

Task/Process

Code Memory

Data Memory Stack Registers


Thread 1
void main (void) { //Create child thread 1 CreateThread(NULL, 1000,(LPTHREAD_STA RT_ROUTINE ) ChildThread 1,NULL, 0, &dwThreadID ); //Create child thread 2 CreateThread(NULL, 1000,(LPTHREAD_STA RT_ROUTINE ) ChildThread 2,NULL, 0, &dwThreadID ); }

Stack Registers
Thread 2
int ChildThread 1 (void) { //Do something }

Stack Registers
Thread 3
int ChildThread 2 (void) { //Do something

Thread Standards Thread standards deal with the different standards available for thread creation and management. These standards are utilized by the Operating Systems for thread creation and thread management. It is a set of thread class libraries. The commonly available thread class libraries are POSIX Threads: POSIX stands for Portable Operating System Interface. The POSIX.4 standard deals with the Real Time extensions and POSIX.4a standard deals with thread 06 ECL 57 26

AES Lab manual

REVA ITM

extensions. The POSIX standard library for thread creation and management is Pthreads. Pthreads library defines the set of POSIX thread creation and management functions in C language. Win32 Threads: Win32 threads are the threads supported by various flavors of Windows Operating Systems. The Win32 Application Programming Interface (Win32 API) libraries provide the standard set of Win32 thread creation and management functions. Win32 threads are created with the API Java Threads: Java threads are the threads supported by Java programming Language. The java thread class Thread is defined in the package java.lang. This package needs to be imported for using the thread creation functions supported by the Java thread class. There are two ways of creating threads in Java: Either by extending the base Thread class or by implementing an interface. Extending the thread class allows inheriting the methods and variables of the parent class (Thread class) only whereas interface allows a way to achieve the requirements for a set of classes

Platform : REDHAT, Fedora 1 1. Create n number of child threads. Each thread prints the message I am in thread number and sleeps for 50 ms/2 sec and then quits. The main thread waits for complete execution of all the child threads and then quits. Compile and execute in Linux. Program 1 Using Threads

/* Pgm to Create "n__ number of child threads. Each thread prints the message _ I m in thread number __ and sleeps for 50msec and then quits. The main thread waits for complete execution of all the child threads and then quits */ #include #include #include #include <stdio.h> <pthread.h> <time.h> <stdlib.h>

# define MAX_THRDS 20 void thread_fn (int *n) { struct timespec stNanoTm; stNanoTm.tv_sec = 0; stNanoTm.tv_nsec = 50; printf ("\nHI I AM IN THREAD %d\n\n",*n); // nanosleep(&stNanoTm,NULL); //for 50 nanoSecs sleep (2); pthread_exit(NULL); } int main () { int iRetVal,iC,n;

06 ECL 57

27

AES Lab manual


pthread_t stId_one[MAX_THRDS]; pthread_attr_t stThrdAttr; pthread_attr_init(&stThrdAttr); pthread_attr_setschedpolicy(&stThrdAttr,SCHED_RR); printf ("Enter the no of threads to be created\n"); scanf ("%d",&n);

REVA ITM

} {

if (n > MAX_THRDS) { printf ("No of threads exceeded max num adjust max value\n"); exit(0); for (iC= 1; iC <= n; iC++) iRetVal = pthread_create(&stId_one[iC],NULL, (void *)thread_fn,(void *)&iC); if (iRetVal != 0) { printf ("creating thread one failed\n"); exit (0); } iRetVal = pthread_join(stId_one[iC],NULL); if (iRetVal != 0) { printf ("Join error\n"); exit (0); }

printf ("TERMINATING MAIN\n"); exit(0); }

Procedure : 1. 2. 3. 4. 5. 6. 7.

Open applications, system tools, & terminals Open file vi filename.c Write the program save & quit :wq compile the file : cc l pthread filename.c check the output ./a.out Enter the No of threads : 05/20

Result : HI I AM IN THREAD 1 06 ECL 57 28

AES Lab manual HI I AM IN THREAD 2 HI I AM IN THREAD 3 . . . HI I AM IN THREAD 20 Terminating Main.

REVA ITM

2. Implement the multithread application satisfying the following : i. Two child threads are created with normal priority. ii. Thread 1 receives and prints its priority and sleeps for 50ms and then quits. iii. Thread 2 prints the priority of the thread 1 and rises its priority to above normal and retrieves the new priority of thread 1, prints it and then quits. iv. The main thread waits for the child thread to complete its job and quits.
/ ********************************************************************************************* *********************************************/ /* * Implementnt the multithread application satisfying the following : * Two child threads are crated with normal priority. * Thread 1 receives and prints its priority and * sleeps for 50ms/2 second and then quits. * Thread 2 prints the priority of the thread 1 * and rises its priority to above normal and retrieves * the new priority of thread 1, prints it and then quits. * The main thread waits for the child thread to complete its job and quits */ / ********************************************************************************************* **********************************************/ #include <stdio.h> #include <pthread.h> #include <time.h> #include <stdlib.h> #include <string.h> # define SCHED_POLICY SCHED_RR struct stThrd_ids { pthread_t id_one; pthread_t id_two; };

06 ECL 57

29

AES Lab manual


void thread_fn_one (int priority) { printf ("\nInside Thread 1\n"); printf ("HI PRIORITY OF THREAD1 is %d\n",priority); sleep(2); pthread_exit(NULL); } void thread_fn_two (struct stThrd_ids *pstThrd_ids) { int n; int iRetVal; struct sched_param param; printf ("\nInside Thread 2\n"); iRetVal = pthread_getschedparam(pstThrd_ids->id_one, &n, &param); if (iRetVal != 0) { printf ("pthread_getschedparam1 error\n"); exit (0); } printf ("Priority of THREAD1 is %d\n",param.sched_priority); pthread_setschedprio(pstThrd_ids->id_one,param.sched_priority+10); iRetVal = pthread_getschedparam(pstThrd_ids->id_one, &n, &param); if (iRetVal != 0) { printf ("pthread_getschedparam2 error\n"); exit (0); } printf ("New Priority of THREAD1 is %d\n",param.sched_priority); pthread_exit(NULL); } int main () { pthread_t stId_one; pthread_t stId_two; pthread_attr_t stThrdAttr; struct sched_param stThrdParm; struct stThrd_ids stThrd_ids; int rr_min_priority; int rr_max_priority; int iRetVal; int iC; memset(&stThrdAttr,0,sizeof(stThrdAttr)); memset(&stThrdParm,0,sizeof(stThrdParm));

REVA ITM

06 ECL 57

30

AES Lab manual


pthread_attr_init(&stThrdAttr); pthread_attr_setschedpolicy(&stThrdAttr,SCHED_POLICY); rr_min_priority = sched_get_priority_min (SCHED_POLICY); rr_max_priority = sched_get_priority_max (SCHED_POLICY); stThrdParm.sched_priority =(rr_min_priority + rr_max_priority)/2; printf ("SCHED_RR priority range is %d to %d:\n",rr_min_priority,rr_max_priority); pthread_attr_setschedparam(&stThrdAttr,&stThrdParm); pthread_attr_setinheritsched (&stThrdAttr,PTHREAD_EXPLICIT_SCHED);

REVA ITM

iRetVal = pthread_create(&stId_one,&stThrdAttr,(void *)&thread_fn_one, (void *)stThrdParm.sched_priority); if (iRetVal != 0) { printf ("Thrd1 create Error\n"); exit (0); } stThrd_ids.id_one = stId_one; iRetVal = pthread_create (&stId_two,&stThrdAttr, (void *)thread_fn_two, (void *)&stThrd_ids); if (iRetVal != 0) { printf ("Thrd2 create Error\n"); exit (0); } iRetVal = pthread_join(stId_one,NULL); if (iRetVal != 0) { printf ("Thread1 Join error\n"); exit (0); } iRetVal = pthread_join(stId_two,NULL); if (iRetVal != 0) { printf ("Thread2 Join error\n"); exit (0); } printf ("\nTERMINATING MAIN\n"); exit(0); }

Procedure : 1. 2. 3. 4. 5. 6.

Open applications, system tools, & terminals Open file vi filename.c Write the program save & quit :wq compile the file : cc l pthread filename.c check the output ./a.out

06 ECL 57

31

AES Lab manual Result :

REVA ITM

IPC Shared Memory Processes share some area of the memory to communicate among them Information to be communicated by the process is written to the shared memory area Processes which require this information can read the same from the shared memory area Same as the real world concept where a Notice Board is used by the college to publish the information for students (The only exception is; only college has the right to modify the information published on the Notice board and students are given Read only access. Meaning it is only a one way channel)

Process

Shared M emory Area

Process

IPC Shared Memory: Pipes Pipe is a section of the shared memory used by processes for communicating. Pipes follow the client-server architecture. A process which creates a pipe is known as pipe server and a process which connects to a pipe is known as pipe client. A pipe can be considered as a conduit for information flow and has two conceptual ends. It can be unidirectional, allowing information flow in one direction or bidirectional allowing bi-directional information flow. A unidirectional pipe allows the process connecting at one end of the pipe to write to the pipe and the process connected at the other end of the pipe to read the data, whereas a bi-directional pipe allows both reading and writing at one end The implementation of Pipes is OS dependent. Microsoft Windows Desktop Operating Systems support two types of Pipes for Inter Process Communication. Namely; Anonymous Pipes: The anonymous pipes are unnamed, unidirectional pipes used for data transfer between two processes. Named Pipes: Named pipe is a named, unidirectional or bi-directional pipe for data exchange between processes. Like anonymous pipes, the process which creates the named pipe is known as pipe server. A process which connects to the named pipe is known as pipe client. With named pipes, any process can act as both client and server allowing point-to-point communication. Named pipes can be used for communicating between processes running on the same machine or between processes running on different machines connected to a network

06 ECL 57

32

AES Lab manual


Process 1 Write Pipe (Named/un-named) Process 2 Read

REVA ITM

3. Implement the usage of anonymous pipe with 512 bytes for data sharing between parent and child processes using handle inheritance mechanism.

MODULE: pipe.c *****************************************************************************/ #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = "Hello, world!\n"; char readbuffer[80]; pipe(fd); if((childpid = fork()) == -1) { perror("fork"); exit(1); } if(childpid == 0) { /* Child process closes up input side of pipe */ close(fd[0]); /* Send "string" through the output side of pipe */ write(fd[1], string, strlen(string)); exit(0); } else { /* Parent process closes up output side of pipe */ close(fd[1]); /* Read in a string from the pipe */ nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); printf("Received string: %s", readbuffer); } return(0); }

Procedure : 1. 2. Open applications, system tools, & terminals Open file vi filename.c 33

06 ECL 57

AES Lab manual 3. 4. 5. Result : Write the program save & quit :wq Compile the file using gcc filename.c Run ./a.out

REVA ITM

IPC Shared Memory: Memory Mapped Objects A shared memory technique adopted by certain Real Time Operating Systems for allocating a shared block of memory which can be accessed by multiple process simultaneously (of course certain synchronization techniques should be applied to prevent inconsistent results). A mapping object is created and physical storage for it is reserved and committed. A process can map the entire committed physical area or a block of it to its virtual address space All read and write operation to this virtual address space by a process is directed to its committed physical area Any process which wants to share data with other processes can map the physical memory area of the mapped object to its virtual memory space and use it for sharing the data. 4. Test the program application for creating an anonymous pipe with 512 bytes of size and pass the Read Handle of the pipe to a second process using memory mapped object. The first process writes a message Hi from Pipe Server. The 2nd process reads the data written by the pipe server to the pipe and displays it on the console. Use event object for indicating the availability of data on the pipe and mutex objects for synchronizing the access in the pipe.
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <poll.h> #include <linux/stat.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h>

06 ECL 57

34

AES Lab manual


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

REVA ITM

/* according to X/OPEN we have to define it ourselves */ union semun { int val; struct semid_ds *buf; unsigned short *array; /* value for SETVAL */ /* buffer for IPC_STAT, IPC_SET */ /* array for GETALL, SETALL */

/* Linux specific part: */ struct seminfo *__buf; }; /* buffer for IPC_INFO */

int main (void) { signed int signed int pid_t char char signed int void union semun iRetVal; iFd[2]; tChildpid; cString[] = "Hi from Pipe Server"; cReadbuffer[40]; iSemId; *pvAddr; suArg;

struct sembuf stSemBuf; struct pollfd stPollFd;

#if 1

06 ECL 57

35

AES Lab manual


iRetVal = pipe(iFd); if (iRetVal != 0) { return -1; } #endif /* Creating semaphore if not created*/

REVA ITM

if((iSemId = semget(9876, 1, 0666 | IPC_CREAT)) == -1) { perror("SIGIPC:CrtSmp-semget:"); return -1; }

/*initializing semaphore 0 to 0 */ suArg.val = 0; if(semctl(iSemId, 0, SETVAL, suArg) == -1) { perror("SIGIPC:CrtSmp-semctl:"); return -1; }

if((tChildpid = fork()) == -1) { perror("fork"); exit(1); }

06 ECL 57

36

AES Lab manual

REVA ITM

/* Child execution */ if(tChildpid == 0) { /* Child process closes up input side of pipe */ close(iFd[1]); stPollFd.fd = iFd[0]; //stPollFd.fd = iFd; stPollFd.events = POLLIN;

while ( poll(&stPollFd, 1, -1) > 0 ) /* infinite wait */ { if (stPollFd.revents && POLLIN) { /* Setting semaphore flag*/ stSemBuf.sem_flg = 0; /* Setting Semaphore number */ stSemBuf.sem_num = 0; /* Decrementing semaphore count*/ stSemBuf.sem_op = -1;

/* Locking Semaphore*/ if(semop(iSemId, &stSemBuf, 1) == -1) { perror("SIGIPC:SmpLock-semop:"); return -1;

06 ECL 57

37

AES Lab manual


} #if 0

REVA ITM

//pvAddr = mmap(0, 80, PROT_NONE, MAP_FILE,iFd[0],0); pvAddr = mmap(0, 80, PROT_NONE, MAP_FILE,iFd,0); perror("SIGIPC:SmpLock-semop:"); printf("PVADDR :%d: :%p:\n",iFd, pvAddr); iRetVal = 0; while(iRetVal < 80) { putchar(*((char *)pvAddr + iRetVal)); iRetVal++; if (*((char *)pvAddr + iRetVal) == 0) { break; } } #endif read(iFd[0], cReadbuffer, sizeof(cReadbuffer) ); printf("%s\n",cReadbuffer); /* Incrementing semaphore count*/ stSemBuf.sem_op = 1; /* Performing release opearation on semaphore */ if(semop(iSemId, &stSemBuf, 1) == -1) { perror("SIGIPC:SmpRel-semop1"); return -1;

06 ECL 57

38

AES Lab manual


} close(iFd[0]); //close(iFd); exit(0); } } } /* Parent */ else { /* Parent process closes up output side of pipe */ close(iFd[0]);

REVA ITM

/* Send "string" through the output side of pipe */ write(iFd[1], cString, (strlen(cString)+1)); //write(iFd, cString, (strlen(cString)+1));

/* Incrementing semaphore count*/ stSemBuf.sem_op = 1;

/* Performing release opearation on semaphore */ if(semop(iSemId, &stSemBuf, 1) == -1) { perror("SIGIPC:SmpRel-semop2"); return -1; }

06 ECL 57

39

AES Lab manual


wait(&iRetVal); close(iFd[1]); //close(iFd); /*wait for child */ }

REVA ITM

/* delete Semaphore */ if(semctl(iSemId, 0, IPC_RMID ) == -1) { perror("SIGIPC:DelSmp-semctl:"); return -1; } return 0; }

Procedure : 1 Open applications, system tools, & terminals 2. Open file vi filename.c 3 Write the program, save & quit :wq 4 Compile the file using gcc filename.c 5 Run ./a.out

Result :

IPC Message Passing: Message Queues

06 ECL 57

40

AES Lab manual

REVA ITM

Process which wants to talk to another process posts the message to a First-In-First-Out (FIFO) queue called Message queue, which stores the messages temporarily in a system defined memory object, to pass it to the desired process Messages are sent and received through send (Name of the process to which the message is to be sent, message) and receive (Name of the process from which the message is to be received, message) methods The messages are exchanged through a message queue The implementation of the message queue, send and receive methods are OS kernel dependent.

M sg Q u e ae u e s e
S e n d M e s s a g e

e g a s s e M e v ie c e R

P cs r es o

P cs r es o

6 5. Create a POSIX based message queue for communicating between two tasks as per the requirements given below:0 i. Use a named message queue with name MyQueue. 1 ii. Create two tasks(Task1 & Task2) with stack size 4000 & priorities 99 & 100 respectively. 2 iii. Task 1 creates the specified message queue as Read Write and reads the message present, if any, from the message queue and prints it on the console. 3 iv. Task2 open the message queue and posts the message Hi from Task2.
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h>

#define MSGSZ

128

06 ECL 57

41

AES Lab manual

REVA ITM

/* * Declare the message structure. */

typedef struct msgbuf { long char } message_buf; mtype; mtext[MSGSZ];

main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length;

/* Get the message queue id for the "name" 1234, which was created by the server. */ key = 1234;

(void) fprintf(stderr, "\nmsgget: MyQueue(%#lx,\%#o)\n", key, msgflg);

06 ECL 57

42

AES Lab manual

REVA ITM

if ((msqid = msgget(key, msgflg )) < 0) { perror("msgget"); return (1); } else (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);

/* * We'll send message type 1 */

sbuf.mtype = 1; (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); (void) strcpy(sbuf.mtext, "Hi from task "); (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid); buf_length = strlen(sbuf.mtext) + 1 ;

/*

* Send a message.*/

if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd"); return (2);

06 ECL 57

43

AES Lab manual


} else printf("Message: \"%s\" Sent\n", sbuf.mtext); return (0); }

REVA ITM

06 ECL 57

44

You might also like