57
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 1

AESLABmodlat

Embed Size (px)

Citation preview

Page 1: AESLABmodlat

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 1

Page 2: AESLABmodlat

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 2

Page 3: AESLABmodlat

AES Lab manual REVA ITM

Birth of commercial EDA

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 3

Page 4: AESLABmodlat

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 likeCadence, 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

06 ECL 57 4

Page 5: AESLABmodlat

AES Lab manual REVA ITM

1. Starting a New Schematic Project

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 5

Page 6: AESLABmodlat

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

Page 7: AESLABmodlat

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 7

Page 8: AESLABmodlat

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 tool2. Open File , New Project, give the name as CMOSCPU3. Check an empty schematic page and a project window like the following

workspace4. Open Page1 schematic

5 Place a 80c51 microcontroller part by using Place part

06 ECL 57 8

Page 9: AESLABmodlat

AES Lab manual REVA ITM

6. 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.,

7. Using Place Net and do the circuit connections of all the components net connections

8. Place GND and VCC connections and connect GND and VCC connections of the circuit schematics.

9. Using placing page connectors connect page 1 net to page 2 and page 3 schematics.

10. Check/Run the DRC(Design rules check) of page111. 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 Check for any errors14 Create/Run Netlist using .mnl format or .net format

06 ECL 57 9

Page 10: AESLABmodlat

AES Lab manual REVA ITM

15 Create/Run Bill of Materials 16 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 tool2. Open File , New Project, give the name as FULLADD3. Check an empty schematic page and a project window like the following

workspace4. Open Page1 schematic5. Draw two Half adder circuit in page 1.6. Place 74LS 32 OR gate7. 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 components10.Run Design Rule Check for the entire project.11. Check for any errors12.Create/Run Netlist using .mnl format or .net format13.Check the schematics with netlist.

06 ECL 57 10

Page 11: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 11

Page 12: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 12

Page 13: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 13

Page 14: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 14

Page 15: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 15

Page 16: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 16

Page 17: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 17

Page 18: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 18

Page 19: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 19

Page 20: AESLABmodlat

AES Lab manual REVA ITM

06 ECL 57 20

Page 21: AESLABmodlat

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

Embedded system RTOS

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

User Applications

Underlying Hardware

Memory Management

Process Management

Time Management

File System Management

I/O System Management Ker

nel

Ser

vice

sApplication Programming

Interface (API)

Device Driver Interface

Page 22: AESLABmodlat

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 SystemsDepending 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 system’s resources Windows CE, QNX, VxWorks MicroC/OS-II etc are examples of Real Time Operating

Systems (RTOS)

06 ECL 57 22

Page 23: AESLABmodlat

AES Lab manual REVA ITM

Features of RTOS

a. Multitasking with preemptive task schedulingb. Round Robin and Time-Sliced scheduling within same priority levelc. Support for static and dynamically created tasksd. Fixed or dynamically changeable task prioritiese. Intertask communication and synchronization via semaphores, messages, and

queuesf. Efficient timer management Timeouts on many servicesg. Management of memoryh. Resource managementi. Fast context switchj. Small RAM and ROM requirementsk. Standard programmer interface on all processorsl. 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. 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

06 ECL 57 23

Page 24: AESLABmodlat

AES Lab manual REVA ITM

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

06 ECL 57 24

Created

Ready

Running

Completed

Blocked

Incepted into memory

Scheduled for Execution

Inte

rrupt

ed o

r Pr

eem

pted

Execution Completion

Page 25: AESLABmodlat

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.

Efficient CPU utilization. The CPU is engaged all time.

06 ECL 57 25

Page 26: AESLABmodlat

AES Lab manual REVA ITM

Code Memory

Data Memory

Task/Process

Thread 1

void main (void){//Create child thread 1CreateThread(NULL,1000,(LPTHREAD_START_ROUTINE)ChildThread1,NULL, 0, &dwThreadID);//Create child thread 2CreateThread(NULL,1000,(LPTHREAD_START_ROUTINE)ChildThread2,NULL, 0, &dwThreadID);}

Thread 2

int ChildThread1 (void){//Do something

}

Thread 3

int ChildThread2 (void){//Do something

}

Stack

Registers

Stack

Registers

Stack

Registers

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 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.

06 ECL 57 26

Page 27: AESLABmodlat

AES Lab manual REVA ITM

• 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 <stdio.h>#include <pthread.h>#include <time.h>#include <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 nanoSecssleep (2);

pthread_exit(NULL);}

int main () { int iRetVal,iC,n; pthread_t stId_one[MAX_THRDS]; pthread_attr_t stThrdAttr;

06 ECL 57 27

Page 28: AESLABmodlat

AES Lab manual REVA ITM

pthread_attr_init(&stThrdAttr); pthread_attr_setschedpolicy(&stThrdAttr,SCHED_RR);

printf ("Enter the no of threads to be created\n");scanf ("%d",&n);

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. Open applications, system tools, & terminals2. Open file vi filename.c3. Write the program4. save & quit :wq5. compile the file : cc – l pthread filename.c6. check the output ./a.out7. Enter the No of threads : 05/20

Result : HI I AM IN THREAD 1

HI I AM IN THREAD 2

06 ECL 57 28

Page 29: AESLABmodlat

AES Lab manual REVA ITM

HI I AM IN THREAD 3...HI I AM IN THREAD 20

Terminating Main.

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;

};

void thread_fn_one (int priority) {

printf ("\nInside Thread 1\n");

06 ECL 57 29

Page 30: AESLABmodlat

AES Lab manual REVA ITM

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));

pthread_attr_init(&stThrdAttr); pthread_attr_setschedpolicy(&stThrdAttr,SCHED_POLICY);

rr_min_priority = sched_get_priority_min (SCHED_POLICY);

06 ECL 57 30

Page 31: AESLABmodlat

AES Lab manual REVA ITM

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);

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. Open applications, system tools, & terminals2. Open file vi filename.c3. Write the program4. save & quit :wq5. compile the file : cc – l pthread filename.c6. check the output ./a.out

Result :

06 ECL 57 31

Page 32: AESLABmodlat

AES Lab manual 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)

Shared Memory Area Process 2Process 1

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

Pipe(Named/un-named)

Process 1Write

Process 2Read

06 ECL 57 32

Page 33: AESLABmodlat

AES Lab manual 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. Open applications, system tools, & terminals2. Open file vi filename.c3. Write the program save & quit :wq4. Compile the file using gcc filename.c5. Run ./a.out

Result :

06 ECL 57 33

Page 34: AESLABmodlat

AES Lab manual 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 areaAny 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>

#include <sys/stat.h>

#include <sys/mman.h>

06 ECL 57 34

Page 35: AESLABmodlat

AES Lab manual REVA ITM

/* according to X/OPEN we have to define it ourselves */

union semun {

int val; /* value for SETVAL */

struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */

unsigned short *array; /* array for GETALL, SETALL */

/* Linux specific part: */

struct seminfo *__buf; /* buffer for IPC_INFO */

};

int main (void)

{

signed int iRetVal;

signed int iFd[2];

pid_t tChildpid;

char cString[] = "Hi from Pipe Server";

char cReadbuffer[40];

signed int iSemId;

void *pvAddr;

union semun suArg;

struct sembuf stSemBuf;

struct pollfd stPollFd;

#if 1

iRetVal = pipe(iFd);

if (iRetVal != 0)

06 ECL 57 35

Page 36: AESLABmodlat

AES Lab manual REVA ITM

{

return -1;

}

#endif

/* Creating semaphore if not created*/

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);

}

/* Child execution */

06 ECL 57 36

Page 37: AESLABmodlat

AES Lab manual REVA ITM

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;

}

#if 0

06 ECL 57 37

Page 38: AESLABmodlat

AES Lab manual 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;

}

close(iFd[0]);

06 ECL 57 38

Page 39: AESLABmodlat

AES Lab manual REVA ITM

//close(iFd);

exit(0);

}

}

}

/* Parent */

else

{

/* Parent process closes up output side of pipe */

close(iFd[0]);

/* 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;

}

wait(&iRetVal);

close(iFd[1]);

06 ECL 57 39

Page 40: AESLABmodlat

AES Lab manual REVA ITM

//close(iFd);

/*wait for child */

}

/* delete Semaphore */

if(semctl(iSemId, 0, IPC_RMID ) == -1)

{

perror("SIGIPC:DelSmp-semctl:");

return -1;

}

return 0;

}

Procedure : 1 Open applications, system tools, & terminals2. Open file vi filename.c3 Write the program, save & quit :wq4 Compile the file using gcc filename.c5 Run ./a.out

Result :

IPC – Message Passing: Message Queues

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

06 ECL 57 40

Page 41: AESLABmodlat

AES Lab manual REVA ITM

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.

Process 1 Process 2

Message Queue

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

Page 42: AESLABmodlat

AES Lab manual REVA ITM

* Declare the message structure.

*/

typedef struct msgbuf

{

long mtype;

char mtext[MSGSZ];

}

message_buf;

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);

if ((msqid = msgget(key, msgflg )) < 0)

06 ECL 57 42

Page 43: AESLABmodlat

AES Lab manual REVA ITM

{

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);

}

else

06 ECL 57 43

Page 44: AESLABmodlat

AES Lab manual REVA ITM

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

return (0); }

06 ECL 57 44