Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
137 views

Spos Lab Manual

The document describes implementing one pass of a two-pass assembler for an 8-bit microprocessor. It includes relevant theory on two-pass assemblers, the tasks performed in each pass, sample code, and the symbol table, literal table, pool table, and intermediate code generated in Pass 1. It also provides an overview of implementing Pass 2 which will take the output of Pass 1 as input and generate the target machine code.

Uploaded by

ishika
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Spos Lab Manual

The document describes implementing one pass of a two-pass assembler for an 8-bit microprocessor. It includes relevant theory on two-pass assemblers, the tasks performed in each pass, sample code, and the symbol table, literal table, pool table, and intermediate code generated in Pass 1. It also provides an overview of implementing Pass 2 which will take the output of Pass 1 as input and generate the target machine code.

Uploaded by

ishika
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 63

Software Laboratory

Assignment No. 1
Title of Assignment:
Design suitable data structures and implement pass-I of a two-pass
assembler for b bit microprocessor/psedo-machine. Implementation
should consist of a few instruction from each category and few assembler
directives
Problem Statement :
Implement one pass-I of TWO Pass assembler with hypothetical Instruction set
using C language. Instruction set should include all types of assembly
language statements such as Imperative, Declarative and Assembler Directive.
While designing stress should be given on
a) How efficiently Mnemonic opcode table could be implemented so
as to enable faster retrieval on op-code.
b) Implementation of symbol table for faster retrieval.
( Concepts in DSF should be applied while design)

Relevant Theory:
1.
Explain what is meant by pass of an assembler.
2.
Explain the need for two pass assembler.
3.
Explain terms such as Forward Reference and backward reference.
4.
Explain various types of errors that are handled in two different passes.
5.
Explain the need of Intermediate Code generation and the variants used.
6.
State various tables used and their significance in the design of two pass
Assembler.
Implementation Logic:
Tasks performed by the passes of two-pass assembler are as follows:

Pass I: -
1. Separate the symbol, mnemonic opcode and operand fields.
2. Determine the storage-required for every assembly language statement
and update the location counter.
3. Build the symbol table and the literal table.
4. Construct the intermediate code for every assembly language statement.

List of hypothetical instructions:

Instruction Assembly Remarks


Opcode mnemonic

00 STOP stop execution

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

1
Software Laboratory

01 ADD first operand modified condition code set


02 SUB first operand modified condition code set
03 MULT first operand modified condition code set
04 MOVER register memory
05 MOVEM memory register
06 COMP sets condition code
07 BC branch on condition code
08 DIV analogous to SUB
09 READ first operand is not used.
10 PRINT first operand is not used.

Algorithm/Pseudo code:
Pass I Algorithm (Assembler First Pass)

a. loc_cntr := 0; (default value)


pooltab_ptr :=1; POOLTAB[1]:=1;
littab_ptr:=1;

b. While next statement is not an END statement

a) If label is present then


{
this_label:= symbol in label field;
Enter(this_label, loc_cntr) in SYMTAB.
}

b) If an LTORG statement then


{
i Process literals
LITTAB[POOLTAB[pooltab_ptr]…LITTAB[lit_tab_ptr-1] to
allocate memory and put the address in the address field.
Update location counter accordingly.
ii pooltab_ptr := pooltab_ptr +1;
iii POOLTAB[pooltab_ptr]:=littab_ptr;
}

c) If START or ORIGIN statement then


{
loc_cntr := value specified in the operand field;
}

d) If an EQU statement then


Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

2
Software Laboratory

{
i. this_addr := value of <address_spec>;
ii. Correct the symbtab entry for this_label to
(this_label,this_addr).
}

e) If a declaration statement then


{
i. code:= code of the declaration statement;
ii. size := size of memory are required by DC/DS
iii. loc_cntr := loc_cntr + size;
iv. Generate IC ‘(DL, code)…’
}

f) If an imperative statement then


i. code:= machine opcode from OPTAB;
ii. loc_cntr := loc_cntr + instruction length from OPTAB;
iii. If operand is a literal then
{
this_literal := literal in operand field;
LITTAB[littab_ptr]:= this_literal;
littab_ptr= littab_ptr +1;
}
else (i.e. operand is a symbol)
{
this_entry := SYMTAB entry number of operand
Generate IC ‘(IS,code)(S,this_entry)’;
}
3.
a) Perform step 2(b).

b) Generate IC’(AD, 02)’.

c) Go to Pass II.

Testing:
SAMPLE PROGRAM Input
START 200
READ A
READ B
MOVER AREG, ='5'
MOVER AREG, A

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

3
Software Laboratory

ADD AREG, B
SUB AREG, ='6'
MOVEM AREG, C
PRINT C
LTORG
MOVER AREG, ='15'
MOVER AREG, A
ADD AREG, B
SUB AREG, ='16'
DIV AREG, ='26'
MOVEM AREG, C
A DS 1
B DS 1
C DS 1
STOP
END Symbol Table
-------------------------------------------------------------
Symb Addr Decl Used Val Len
-------------------------------------------------------------
A 216 1 1 0 1
B 217 1 1 0 1
C 218 1 1 0 1
-------------------------------------------------------------
Total Errors: 0
Total Warnings: 0
Literal Table
------------------------------------
Lit# Lit Addr
------------------------------------
00 ='5' 208
01 ='6' 209
02 ='15' 220
03 ='16' 221
04 ='26' 222
------------------------------------
Pool Table
--------------------
Pool# Pool Base
--------------------
00 0
01 2
------------------------

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

4
Software Laboratory

INTERMEDIATE CODE
Intermediate Code
(AD, 00) (C, 200)
(IS, 09) (S, 00)
(IS, 09) (S, 01)
(IS, 04) (0) (L, 00)
(IS, 04) (0) (S, 00)
(IS, 01) (0) (S, 01)
(IS, 02) (0) (L, 01)
(IS, 05) (0) (S, 02)
(IS, 10) (S, 02)
(AD, 04)
(IS, 04) (0) (L, 02)
(IS, 04) (0) (S, 00)
(IS, 01) (0) (S, 01)
(IS, 02) (0) (L, 03)
(IS, 08) (0) (L, 04)
(IS, 05) (0) (S, 02)
(DL, 01) (C, 01)
(DL, 01) (C, 01)
(DL, 01) (C, 01)
(IS, 00)
(AD, 01)
Conclusion:
Thus we have implemented the one pass-I of II pass Assembler using C
language.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

5
Software Laboratory

Assignment No. 2
Title of Assignment:
Implement pass-II of a two-pass assembler for 8 bit
microprocessor/pseudo-machine. The output of assignment-1
(intermediate file and symbol table) should be input for this assignment.
Problem Statement(s) :
Implement one pass-II of TWO Pass assembler with hypothetical Instruction
set using C language. Instruction set should include all types of assembly
language statements such as Imperative, Declarative and Assembler Directive.
While designing stress should be given on
a) How efficiently Mnemonic opcode table could be implemented so
as to enable faster retrieval on op-code.
b) Implementation of symbol table for faster retrieval.
( Concepts in DSF should be applied while design)

Relevant Theory:
1 .Explain what is meant by pass of an assembler.
2. Explain the need for two pass assembler.
3. Explain terms such as Forward Reference and backward reference.
4. Explain various types of errors that are handled in two different passes.
5. Explain the need of Intermediate Code generation and the variants used.
6. State various tables used and their significance in the design of two pass
Assembler
Implementation Logic :

Pass II Algorithm

It has been assumed that the target code is to be assembled in the named
code_area.

1. code_area_address := address of code_area;


Pooltab_ptr :=1;

Loc_cntr:=0;
2. While next statement is not an END statement
(a) Clear machine_code_buffer;

b) If an LTORG statement
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

6
Software Laboratory

(i) Process literals in LITTAB[POOLTAB[pooltab_ptr]]…


LITTAB[POOLTAB[pooltab_ptr+1]]-1 similar to processing of constants in a DC
statement i.e. assemble the literals in machine_code_buffer.
(ii) size := size of memory area required for literals;
(iii) pooltab_ptr:= pooltab_ptr +1;
(c) If a START or ORIGIN statement then
(i) loc_cntr := value specified in operand field;
(ii) size:=0;
(d) If a declaration statement
(i) If a DC statement then
Assemble the constant in machine_code_buffer.
(ii) size: = size of memory area required by DC/DS;
(e) If an imperative statement
(i) Get operand address from SYMTAB or LITTAB.
(ii) Assemble instruction in machine_code_buffer.
(iii) size: = size of instruction;
(f) if size not equal to 0 then
(i) Move contents of Machine_code_buffer to the address
code_area_address + loc_cntr;
(ii) loc_cntr := loc_cntr + size;
3. (Processing of END statement)
(a) Perform steps 2(b) and 2(f).
(b) Write code_area into output file.

Implementation Logic :

Data structures required for II PASS Assembler

char OPTAB[][6] = { "STOP","ADD","SUB","MULT","MOVER","MOVEM",


"COMP","BC","DIV","READ","PRINT"};

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

7
Software Laboratory

char REGTAB[][5] = { "AREG","BREG","CREG","DREG"};


char CONDTAB[][4] = { "LT","LE","EQ","GT","GE","ANY"};
char ADTAB[][7] = { "START","END","ORIGIN","EQU","LTORG" };

Error Handling to be done:

Forward reference (Symbol used but not defined): -


This error occurs when some symbol is used but it is not defined into the
program.
Duplication of Symbol (Multiple declaration): -
This error occurs when some symbol is declared more than once in the
program.
Mnemonic error (Invalid instruction):
If there is invalid instruction then this error will occur.
Register error (Invalid register):
If there is invalid register then this error will occur.
Operand error: -
This error will occur when there is an error in the operand field.

Pass II: -
Synthesize the target code by processing the intermediate code
generated during
Testing:
Testing:
SAMPLE PROGRAM Input
START 200
READ A
READ B
MOVER AREG, ='5'
MOVER AREG, A
ADD AREG, B
SUB AREG, ='6'
MOVEM AREG, C
PRINT C
LTORG
MOVER AREG, ='15'
MOVER AREG, A
ADD AREG, B
SUB AREG, ='16'

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

8
Software Laboratory

DIV AREG, ='26'


MOVEM AREG, C
A DS 1
B DS 1
C DS 1
STOP
END Symbol Table
-------------------------------------------------------------
Symb Addr Decl Used Val Len
-------------------------------------------------------------
A 216 1 1 0 1
B 217 1 1 0 1
C 218 1 1 0 1
-------------------------------------------------------------
Total Errors: 0
Total Warnings: 0
Literal Table
------------------------------------
Lit# Lit Addr
------------------------------------
00 ='5' 208
01 ='6' 209
02 ='15' 220
03 ='16' 221
04 ='26' 222
------------------------------------
Pool Table
--------------------
Pool# Pool Base
--------------------
00 0
01 2
--------------------
INTERMEDIATE CODE
Intermediate Code
(AD, 00) (C, 200)
(IS, 09) (S, 00)
(IS, 09) (S, 01)
(IS, 04) (0) (L, 00)
(IS, 04) (0) (S, 00)
(IS, 01) (0) (S, 01)
(IS, 02) (0) (L, 01)
(IS, 05) (0) (S, 02)
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

9
Software Laboratory

(IS, 10) (S, 02)


(AD, 04)
(IS, 04) (0) (L, 02)
(IS, 04) (0) (S, 00)
(IS, 01) (0) (S, 01)
(IS, 02) (0) (L, 03)
(IS, 08) (0) (L, 04)
(IS, 05) (0) (S, 02)
(DL, 01) (C, 01)
(DL, 01) (C, 01)
(DL, 01) (C, 01)
(IS, 00)
(AD, 01)

PASS II OUTPUT

Target Code
200) + 09 0 216
201) + 09 0 217
202) + 04 0 208
203) + 04 0 216
204) + 01 0 217
205) + 02 0 209
206) + 05 0 218
207) + 10 0 218
208) + 00 0 005
209) + 00 0 006
210) + 04 0 220
211) + 04 0 216
212) + 01 0 217
213) + 02 0 221
214) + 08 0 222
215) + 05 0 218
216)
217)
218)
219) + 00 0 000
220) + 00 0 015
221) + 00 0 016
222) + 00 0 026

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

10
Software Laboratory

Conclusion:
Thus we have implemented the one pass-II of II pass Assembler using C
language.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

11
Software Laboratory

Assignment No. 3
Title of Assignment:
Design suitable data structures and implement pass-I of a two-pass macro-
processor.
Problem Statement(s) :
Implement the program for pass-I of a two pass macro-processor using c
language.
Relevant Theory:
1. Explain what is meant by pass of macro-processor.

2. Explain the need for one-I of two pass macro-processor.

3. Explain macro, macro definition, macro call, macro expansion,


conditional macro expansion.

4. Explain various types of errors that are handled in two different


passes.

5. Explain positional arguments, keyword arguments.

6. State various tables used and their significance in the design of two
pass macro-processor.

7. Define the term macro.

8. Distinguish between macro and a subroutine

9. Define and Distinguish between parameters that can be used in


Macros.
10. State various tables used in processing the macro.

11. Explain the role of stack in nested macros


Macro facility:
An assembly language macro facility is to extend the set of operations
provided in an assembly language.
In order that programmers can repeat identical parts of their program
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

12
Software Laboratory

macro facility can be used. This permits the programmer to define an


abbreviation for a part of program & use this abbreviation in the
program. This abbreviation is treated as macro definition & saved by the
macro processor. For all occurrences the abbreviation i.e. macro call,
macro processor substitutes the definition.

Macro definition part:

It consists of
1. Macro Prototype Statement - this declares the name of macro & types
of parameters.
2. Model statement - It is statement from which assembly language
statement is generated during macro expansion.
3. Preprocessor Statement - It is used to perform auxiliary function
during macro expansion.

Macro Call & Expansion:


The operation defined by a macro can be used by writing a macro name
in the mnemonic field and its operand in the operand field. Appearance
of the macro name in the mnemonic field leads to a macro call. Macro
call replaces such statements by sequence of statement comprising the
macro. This is known as macro expansion.
Macro Facilities:

1. Use of AIF & AGO allows us alter the flow of control during expansion.
2. Loops can be implemented using expansion time variables.

Implementation Logic :

1. Definition processing - Scan all macro definitions and for each macro
definition enter the macro name in macro name table (MNT). Store
entire macro definition in macro definition table (MDT) and add
auxiliary information in MNT such as no of positional parameters
(#PP) no of key word parameters (#KP), macro definition table position
(MDTP) etc.
2. Macro expansion - Examine all statement in assembly source
program to detect the macro calls. For each macro call locate the
macro in MNT, retrieve MDTP, establish the correspondence between
formal & actual parameters and expand the macro.

Data structures required for macro definition processing –


1.Macro Name Table [MNT] - Fields- Name of Macro, #PP (no of positional
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

13
Software Laboratory

parameters), #KP( no of keyword parameters), MDTP ( Macro Definition Table


Pointer), Keyword Parameters Default Table Position (KPDTP),
2.Parameter Name Table [PNTAB] - Fields - Parameter Name
3.Keyword parameter Default Table [KPDTAB] - Fields - Parameter Name,
Default value
4.Macro Definition Table [MDT] -
Model Statement are stored in the intermediate code from as:
Opcode, Operands.

Algorithm/Pseudo code:
Before processing any definition initialize KPDTAB_ptr, MDT_ptr to 0 and
MNT_ptr to -1. These table pointers are common to all macro definitions. For
each macro definition perform the following steps.

A one-pass macro processor that alternate between macro definition and macro
expansion in a recursive way is able to handle recursive macro definition.
Because of
the one-pass structure, the definition of a macro must appear in the source
program before any statements that invoke that macro.

Algorithm:
            begin {macro processor}
                        EXPANDING : = FALSE
                                    while OPCODE ≠ ‘END’ do
                                         begin
                                                GETLINE
                                                PROCESSLINE
                                                end  {while}
                                    end {macro processor}
                        procedure PROCESSLINE
                                    begin
                                         search NAMTAB for OPCODE
                                         if found then
                                                EXPAND
                                        else if OPCODE = ‘MACRO’ then
                                                DEFINE
                                        else write source line to expanded file
                                        end {PROCESSLINE}

Algorithm:

procedure EXPAND

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

14
Software Laboratory

            begin
                 EXPANDING : = TRUE
                 get first line of macro definition {prototype} from DEFTAB
                 set up arguments from macro invocation in ARGTAB
                 write macro invocation to expanded file as a comment
                 while not end of macro definition do
                        begin
                             GETLINE
                             PROCESSLINE
                             end {while}
                        EXPANDING : = FALSE
            end  {EXPAND}

procedure GETLINE
            begin
                 if EXPANDING then
                        begin                              get next line of macro definition
from DEFTAB
                             substitute arguments from ARGTAB for positional
notation
                        end {if}
            else
                 read next line from input file
     end {GETLINE}

Algorithm for Macro Definition Processing:

1. Initialize PNTAB – ptr to 0 & fields of MNT, # pp, # kp to 0 and increment


MNT_ptr by 1.
2. For macro prototype statement from MNT entry.
a. Enter name into name field.
b. For each position parameter field
i. Enter name in parameter name table.
ii. Increment PNTAB – ptr by 1.
iii. Increment # pp by 1.
c. KPDTP  KPDTAB - ptr
d. For each keyword parameter
i. Enter name & default value (if any) in KPDTAB[KPDTAB –
ptr].
ii. Increment KPTAB –ptr by 1.
iii. Enter name in PNTAB & increment PNTAB – ptr by 1.
iv. Increment # kp by 1.
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

15
Software Laboratory

e. MDTP  MDT – ptr ( current MDT_Ptr)


3. While not a MEND statement
Read next statement
a. Model statement
i. For parameter generate specification (p, # n).
ii. Record intermediate code in MDT.
iii. Increment MDT - ptr by 1.
end
b. If MEND statement
Begin
Enter MEND in MDT, increment MDT_ptr by 1.
If #kp == 0 then KPDTP = 0
Return to main logic i.e. step 6 of main logic.

Data structures required for expansion processing :-


1. Actual parameter table: APTAB
2. Macro expansion counter : MEC.

Algorithm for macro expansion:


1. Initialization
i. MEC  MDTP from MNT.
ii. Create APTAB with # pp & # kp entries and set APTAB ptr
accordingly.
iii. Copy keyword parameter defaults from KPDTAB in APTAB[pp] to
APTAB[#pp + #kp -1].
iv. Process actual positional parameters in call and copy them in APTAB
from 0 to # pp-1.
v. For keyword parameter specification search name in parameter name
field of KPDTAB, get matching entry in q & enter value in APTAB [ #pp
+ q – KPDTP ].
2. While Statement pointed by MEC in MDT is not MEND.
i. If model statement then replace operands of the form (p, #n) by values
in APTAB.
ii. Increment MEC by one.
iii. Write the model statement on expanded code file.
3. Exit from macro expansion
4.
Main Program Logic :

1. Initialize KPDTAB_ptr, MDT_ptr to 0 and MNT_ptr to -1. These


table pointers are common to all macro definitions ( There could be
more than one macro definition in program)
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

16
Software Laboratory

2. Read the statement from source file, one line at time


3. Separate the words from that line and count the no of words. Save
the separated words in the array say word which is a array of
strings
4. If count for words in a line is one then check if that only word
matches with “MACRO” keyword, if MACRO keyword found then
performs Macro definition processing routine.
5. If it does not match then check whether first word of the line
matches with any of the entries in the macro name table. (Search
the complete macro name table for presence of macro call), if so
then perform Macro expansion routine.
6. If no Macro call or no definition then enter the line as it is in the
expanded code file.
7. If not end of file go to step 3.

Testing:
The assembly language program with macro definitions & macro calls
MACRO
MAC1
MOVER AREG, M
ADD BREG, M
MOVEM CREG, M
MEND
MACRO
EVAL &X,&Y,&Z
MOVER AREG, &X
SUB AREG, &Y
ADD AREG, &Z
MOVER AREG, &Z
MEND
MACRO
CALC &X,&Y,&OP=MULT,&LAB=
&LAB MOVER AREG, &X
&OP AREG, &Y
MOVEM AREG, &X
MEND
START
MOVEM AREG, B
EVAL A, B, C
ADD AREG, N
MOVEM AREG, N
CALC P, Q, LAB=LOOP:
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

17
Software Laboratory

MOVEM AREG, N
MAC1
CALC P,Q,OP=DIV, LAB=NEXT
M DS 1
A DS 5
B DS 1
C DS 1
N DS 1
P DS 1
Q DS 1
END

Sample output: -
Macro name Table

Name #p #kp mdt kpdt


p p p
MAC1 0 0 0 0
EVAL 3 0 4 0
CALC 2 2 9 1

MACRO DEFINITION TABLE

Index Statements of the macros


0 MOVER AREG, M
1 ADD BREG, M
2 MOVEM CREG, M
3 MEND
4 MOVER AREG, (P,0)
5 SUB AREG, (P,1)
6 ADD AREG, (P,2)
7 MOVER AREG, (P,2)
8 MEND
9 (P,3) MOVER AREG, (P,0)
10 (P,2) AREG, (P,1)
11 MOVEM AREG, (P,0)
12 MEND
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

18
Software Laboratory

Expanded code with no macro definition & macro calls.

START
MOVEM AREG, B
+ MOVER AREG, A // expanded code of EVAL
+SUB AREG, B
+ADD AREG, C
+MOVER AREG, C
ADD AREG, N
MOVEM AREG, N
+ LOOP MOVER AREG, P // expanded code for CALC
+MULT AREG, Q
+MOVEM AREG, P
MOVEM AREG,N
+MOVER AREG, M // expanded code for MAC1
+ADD BREG, M
+MOVEM CREG, M
+ NEXT MOVER AREG, P // expanded code for CALC
+DIV AREG, Q
+MOVEM AREG, P
A DS 5
B DS 1
C DS 1
N DS 1
P DS 1
Q DS 1
END

Students are supposed to display PNTAB and APTAB also.

Instructions regarding testing of the program: -


1. Students are expected to take minimum two macro definitions
2. Positional & keywords parameters are to be handled.
3. The code generated from macro expansion should be preceded with + sign.
4. Students should write about error handling. At least following errors should
be handled
a. Positional parameters must precede the keyword parameters
b. Mismatch in total no of parameters in formal and actual parameters.
5. Students should write about error handling.
6. Students are supposed to write assumptions, limitations if any

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

19
Software Laboratory

Conclusion:
Thus we have implemented pass-I of two pass Macro processor using C

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

20
Software Laboratory

Assignment No. 4
Title of Assignment :
Design suitable data structures and implement pass-II of a two-pass
macro-processor.
Problem Statement:
Write a program in C for a pass-II of two pass macro processor for
implementation of Macro Processor.
Following cases to be considered
a) Macro without any parameters
b) Macro with Positional Parameters
c) Macro with Key word parameters
d) Macro with positional and keyword parameters.
( Conditional expansion , nested macro implementation not
expected)

Relevant Theory / Literature Survey:

1. Define the term macro.


2. Distinguish between macro and a subroutine
3. Define and Distinguish between parameters that can be used in
macros.
4. State various tables used in processing the macro.
5. Explain the role of stack in nested macros.
Macro facility:
An assembly language macro facility is to extend the set of
operations provided in an assembly language.
In order that programmers can repeat identical parts of their
program macro facility can be used. This permits the programmer
to define an abbreviation for a part of program & use this
abbreviation in the program. This abbreviation is treated as macro
definition & saved by the macro processor. For all occurrences the
abbreviation i.e. macro call, macro processor substitutes the
definition.

Macro definition part:

It consists of
1. Macro Prototype Statement - this declares the name of macro &

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

21
Software Laboratory

types of parameters
2. Model statement - It is statement from which assembly language
statement is generated during macro expansion.
3. Preprocessor Statement - It is used to perform auxiliary function
during macro expansion.

Macro Call & Expansion:


The operation defined by a macro can be used by writing a macro
name in the mnemonic field and its operand in the operand field.
Appearance of the macro name in the mnemonic field leads to a
macro call. Macro call replaces such statements by sequence of
statement comprising the macro. This is known as macro
expansion.
Macro Facilities:

1. Use of AIF & AGO allows us alter the flow of control during
expansion.
2. Loops can be implemented using expansion time variables.

Testing:
The assembly language program with macro definitions & macro calls
MACRO
MAC1
MOVER AREG, M
ADD BREG, M
MOVEM CREG, M
MEND
MACRO
EVAL &X,&Y,&Z
MOVER AREG, &X
SUB AREG, &Y
ADD AREG, &Z
MOVER AREG, &Z
MEND
MACRO
CALC &X,&Y,&OP=MULT,&LAB=
&LAB MOVER AREG, &X
&OP AREG, &Y
MOVEM AREG, &X
MEND
START
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

22
Software Laboratory

MOVEM AREG, B
EVAL A, B, C
ADD AREG, N
MOVEM AREG, N
CALC P, Q, LAB=LOOP:
MOVEM AREG, N
MAC1
CALC P,Q,OP=DIV, LAB=NEXT
M DS 1
A DS 5
B DS 1
C DS 1
N DS 1
P DS 1
Q DS 1
END

Sample output: -
Macro name Table

Name #p #kp mdt kpdt


p p p
MAC1 0 0 0 0
EVAL 3 0 4 0
CALC 2 2 9 1

MACRO DEFINITION TABLE

Index Statements of the macros


0 MOVER AREG, M
1 ADD BREG, M
2 MOVEM CREG, M
3 MEND
4 MOVER AREG, (P,0)
5 SUB AREG, (P,1)
6 ADD AREG, (P,2)
7 MOVER AREG, (P,2)
8 MEND
9 (P,3) MOVER AREG, (P,0)
10 (P,2) AREG, (P,1)
11 MOVEM AREG, (P,0)
12 MEND
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

23
Software Laboratory

Expanded code with no macro definition & macro calls.

START
MOVEM AREG, B
+ MOVER AREG, A // expanded code of EVAL
+SUB AREG, B
+ADD AREG, C
+MOVER AREG, C
ADD AREG, N
MOVEM AREG, N
+ LOOP MOVER AREG, P // expanded code for CALC
+MULT AREG, Q
+MOVEM AREG, P
MOVEM AREG,N
+MOVER AREG, M // expanded code for MAC1
+ADD BREG, M
+MOVEM CREG, M
+ NEXT MOVER AREG, P // expanded code for CALC
+DIV AREG, Q
+MOVEM AREG, P
A DS 5
B DS 1
C DS 1
N DS 1
P DS 1
Q DS 1
END

Students are supposed to display PNTAB and APTAB also.

Instructions regarding testing of the program: -


1. Students are expected to take minimum two macro definitions
2. Positional & keywords parameters are to be handled.
3. The code generated from macro expansion should be preceded with
+ sign.
4. Students should write about error handling. At least following
errors should be handled
a. Positional parameters must precede the keyword parameters
b. Mismatch in total no of parameters in formal and actual
parameters.
5. Students should write about error handling.
6. Students are supposed to write assumptions, limitations if any
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

24
Software Laboratory

Conclusion:
Thus we have implemented pass-II of two pass Macro processor using C.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

25
Software Laboratory

Assignment No. 5
Title of Assignment :
DLL Creation
Problem Statement:
Write a program to create Dynamic Link Library for any mathematical
operation and write an application program to test it
Relevant Theory / Literature Survey:
1. Explain the need of dll.
2. Explain the console application
3.Explain the various library which is need for creating the dll
4.Explain the method of declaration and definition of method
Design Analysis/ Implementation Logic:

Creating a dll

In this assignment we will consider two sections :

1. create a dll containing four basic mathematical functions

2. create a console application in Visual C++ which links with the dll just
created and uses the function stored in the dll

Part 1 : create a dll

Follow the steps given below :

1. open visual c++ from the start menu

2. From the file menu choose New option.

3. In the New window that appears choose win-32 Dynamic Link library,
give a valid project name for. E.g. say calc_dll and choose a valid project
location if required.

4. In the next windows choose dll project type as “ a simple dll ”

5. Then click ok. Visual C++ editor opens up the project related basic
files.

6. From the left bottom window choose file view instead of class view .

7. Double click calc_dll.cpp file to open it in the editor from the le7t side
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

26
Software Laboratory

Window.

8. include header file “stdexcept” as


#include <stdexcept>

9. Also mention the standard namespace.


Using namespace std;

10. Now declare the function which will be contained in the dll. Here we
will just define a divide function which will accept two numbers and
return their division.

Syntax :
extern “C” __declspec(dllexport)double divide(double,double);
This syntax tells the compiler that this function will be exported with its
formal parameters and the return type.

11. Let the default DllMain () function remains as it is.

12. Now define the function declared above.

For e.g.
double divide(double x, double y)
{
if (y==0)
{
Throw invalid argument (“Divide by zero error !!”);
}
else
{
return x/y;
}
}

13. Now click on the Build icon in standard toolbar or press F7 to build
the dll.

14. It should be built without any error or warning

part II : create console application to use a dll

1. Create one more project from file->new option.


Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

27
Software Laboratory

2. Choose project type as a win32-console application

3. Provide a name and location of the project for .e.g. calc

4. Click OK. In the next window when asked to specify the type of console
application as a “simple hello world” application.

5. Click OK. The Visual C++ editor opens up basic required files.

6. Choose file view instead of class view.

7. Double click calc.cpp to open it in the editor.

8. Now make changes to the code.

9. now first include iostream

#include<iostream>
and the default namespace as :
using namespace std;

10. Declare the function which we will be using by linking to the dll we
just created.

11. Remember that syntax (formal parameters and return type) of the
function declared here and in the dll must be same.

12. type the function declaration :


extern “C” __declspec(dllimport)double divide(double, double);

13. now in the main function use this function as following :


double x,y,result;
//read the two numbers
cin>>x>>y;
result=divide(x,y);

14. Here by making a call to the divide function, the division of the two
numbers is done and the result is stored in the result variable.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

28
Software Laboratory

15. Now as we have not defined the divide () function in this program
rather we are using by linking to a dll .

16. For linking our “calc” program with the dll “calc_dll” we will make use
of the library file created with our “calc_dll”.

17. Go to the project directory of calc_dll. for e.g. it may be :

C:\program files\Microsoft visual studio\my projects\calc_dll

18. in this folder go to the “debug “ folder and copy two files “calc_dll.dll”
and “calc_dll.lib” .

19. paste these two files in our current project directory ‘s debug folder
which path could be like :

C:\program files\Microsoft visual studio\my projects\calc\debug

20. Note that by now the “debug “ folder in the “calc” project directory
should contain our two required files “calc_dll.dll” and “calc_dll.lib”.

21. For linking our program “calc” with the calc_dll we need to include the
calc_dll.lib file into our current project.

22. Select from Project ->Add to Project ->Files.

23. Select the file type as all file types from the file type drop down
window.

24. Browse to debug folder of our current project and select the
“calc_dll.lib”.

25. Now click on Build option button or press F7

26. The project should compile successfully.

27. Now run the application by clicking Run button or press CTRL+F5.
Conclusion:
Thus we have studied dll creation using console application

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

29
Software Laboratory

Assignment No. 6
Title of Assignment :
Deadlock avoidance using Banker's Algorithm.
Problem Statement(s) :
Implement Banker Algorithm for Deadlock avoidance.
Relevant Theory / Literature Survey:

1. Define Deadlock with an example


2. Resource allocation Graph
3. Wait-for-Graph
4. The Banker's algorithm
5. Safe and Unsafe States
6. Deadlock Characterization
7. Deadlock Prevention
8. Deadlock Avoidance
9. Banker’s Algorithm
10. Limitations
Design Analysis/ Implementation Logic:

Data Structures for the Banker’s Algorithm


Let n = number of processes, and m = number of resources types.
 Available: Vector of length m. If available [j] = k, there are k
instances of resource type Rj available.
 Max: n x m matrix. If Max [i,j] = k, then process Pi may request at
mostk instances of resource type Rj.
 Allocation: n x m matrix. If Allocation[i,j] = k then Pi is currently
allocated k instances of Rj
 Need: n x m matrix. If Need[i,j] = k, then Pi may need k more
instances of Rj to complete its task.
Need [i,j]= Max[i,j] – Allocation [i,j].
Safety Algorithm
1. Let Work and Finish be vectors of length m and n, respectively.
Initialize:
Work = Available

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

30
Software Laboratory

Finish [i] = false for i - 1,3, …, n.


2. Find and i such that both:
(a) Finish [i] = false
(b) Needi<=Work
If no such i exists, go to step 4.
3. Work = Work + Allocationi
Finish[i] = true
go to step 2.
4. If Finish [i] == true for all i, then the system is in a safe state.

Resource-Request Algorithm for Process Pi


Request = request vector for process Pi. If Requesti [j] = k then process Pi
wants k instances of resource type Rj.
1. If Requesti <=Needi go to step 2. Otherwise, raise error condition,
since process has exceeded its maximum claim.
2. If Requesti <=Available, go to step 3. Otherwise Pi must wait, since
resources are not available.
3. Pretend to allocate requested resources to Pi by modifying the state as
follows:
Available= Available - Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi – Requesti;;
• If safe state the resources are allocated to Pi.
• If unsafe state Pi must wait, and the old resource-allocation state is
restored

Testing:

Available system resources are:

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

31
Software Laboratory

ABCD

3112

Processes (currently allocated resources):

ABCD

P1 1 2 2 1

P2 1 0 3 3

P3 1 1 1 0

Processes (maximum resources):

ABCD

P1 3 3 2 2

P2 1 2 3 4

P3 1 1 5 0

Can the following request be served by the Resource allocation state?


1. P3(0,0,3,0)
2. P2(0,1,0,0)

Safe sequence is not unique. A different safe sequence may also be


possible.
Conclusion:

Hence we have implemented banker’s algorithm for deadlock avoidance.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

32
Software Laboratory

Assignment No. 7
Title of Assignment :
Simulation of following CPU scheduling algorithms
Problem Statement(s) :
Implement following programs to simulate following CPU scheduling algorithms

a. FCFS
b. SJF (preemptive and non-preemptive)
c. Priority Scheduling (preemptive and non-preemptive)
d. Round Robin Scheduling

Relevant Theory:

Uniprocessor Scheduling

Types of Scheduling

Long term scheduling

Medium Term Scheduling

Short term Scheduling

Non-preemptive Scheduling

Preemptive Scheduling

Explain the following points for each of the Scheduling algorithms:

FCFS, SJF, Priority, Round Robin

Algorithm

Advantages

Disadvantages

Example (Preemptive and Non Preemptive as per relevance)


Implementation Logic :

1. Choose how to represent a process and how to keep track of different


parameters of all processes.
2. Choose with which rules the scheduler will choose the next process
3. Design an algorithm that applies the above rules. Take into
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

33
Software Laboratory

consideration arrival time, priority, quantum, etc. appropriately.


4. Implement the algorithm.

Suggested fields in the structure to represent a Process:


2. Burst_Time
3. Arrival_Time
4. Priority
5. Waiting_Time
6. Turn_A_Time
7. Remaining_Time

An array/linked list of such a structure will store the set of processes for which
CPU scheduling can be applied.
A queue or priority queue using array / linked list has to be appropriately
maintained to implement the algorithms.

Testing:
For the given data [Consider relevant of data depending on the scheduling
algorithm]
Process Arrival Time Burst Time Priority
A 0 3 2
B 2 6 3
C 4 4 4
D 6 5 5
E 8 2 1
Apply the scheduling algorithms like FCFS, (Both Preemptive & Non
Preemptive) SJF, Priority, Round Robin (quantum = 2 ms)

Conclusion:
Thus we have learnt and implemented following programs to simulate the CPU
scheduling algorithms like
a. FCFS
b. SJF (preemptive and non-preemptive)
c. Priority Scheduling (preemptive and non-preemptive)
d. Round Robin Scheduling

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

34
Software Laboratory

Assignment 8
Title of Assignment :
Simulation of Page replacement algorithms ( FIFO, LRU, Optimal)
Problem Statement:
Implement Page replacement algorithms ( FIFO, LRU, Optimal)
Relevant Theory / Literature Survey:

1. Concept of Virtual memory


2. Paging
1. Need of Paging
2. Page fault
3. Page Replacement Algorithms (FIFO, LRU, Optimal,
Clock)
◦ Algorithm
◦ Advantages
◦ Disadvantage
of the 3. Quality of Page replacement algorithm
4. Belady's Anomaly
4. Address Translation in Paging System
5. Thrashing
6. Local and Global Page Replacement algorithm
6. Working set Model
Design Analysis/ Implementation Logic:
FIFO:
Simplest page replacement algorithm
1) Associate a timestamp with each frame
2) Assigned when a page is brought into memory
3) Always throw out the oldest pages
Can also be implemented with a simple FIFO queue to hold all pages in
memory
1) Add new pages by inserting them at the tail
2) Always replace the page at the head

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

35
Software Laboratory

LRU(Least Recently Used) :

1. LRU policy replaces the page in memory that has not been
referenced for the longest time.
2. The LRU algorithm performs better than FIFO. The LRU algorithm
belongs to a larger class of stack replacement algorithms. When
more real memory is made available to the executing program,
stack algorithm therefore do not suffer from Belady’s anomaly.
Optimal Page Replacement:

1. Belady's optimal algorithm for the minimum number of page faults.

2. Replace the page that will be referenced furthest in the future or not at
all.

Testing:
Reference String: 4 3 2 1 4 3 5 4 3 2 1 5
No of Frames: 3 or 4
Conclusion:
Hence we have implemented the page replacement algorithms.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

36
Software Laboratory

Assignment 9
Title of Assignment :
Multithreading Concept
Problem Statement:
Implement Producer-Consumer using multi-threading concept.
Relevant Theory / Literature Survey:

1. Unix Concurrency Mechanism


(Pipes, Messages, Shared memory, Semaphores, Signals)
2. Producer-consumer Problem
3. Bounded Buffer and Unbounded buffer Problem
4. Unnamed and Named pipes
5. Explain the following functions
1. dup(), dup2(), pipe(), 2. popen(), 3. pclose(),

Design Analysis/ Implementation Logic:

Algorithms for Producer-consumer problem (Bounded and Unbounded


buffer)

#DEFINE N 50
typedef int semaphore;
semaphore mutex=1;
semaphore empty=N; semaphore full=0;
void producer(void)
{
int item;
while(TRUE)
{
item=producer_item( )
down(&empty);
down(&mutex);
insert_item(item);
up(&mutex);
up(&full);
}
}

void consumer(void)

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

37
Software Laboratory

int item;
while(TRUE)
{
down(&full);
down(&mutex);
item=remove_item( );
up(&mutex);
up(&empty);
consume_item(item);
}
}

Conclusion:
Inter-process Communication for Producer-Consumer problem in UNIX
(Pipes or Shared Memory) has been implemented.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

38
Software Laboratory

Assignment No. 10
Title of Assignment :
Multithreading Concept.
Problem Statement:
Implement Reader-Writer problem using multi-threading concept.
Relevant Theory / Literature Survey:

1. Concept of Mutual Exclusion


2. Semaphores (
3. Monitors
4. Reader-Writer problem
5. Dining philosophers problem
6. POSIX Library

Design Analysis/ Implementation Logic:

Algorithms for reader-Writer problem

typedef int semaphore;


semaphore mutex=1
semaphore db=1
int rc=0;
void reader(void)
{
while(TRUE)
{
down(&mutex)
rc=rc+1;
if(rc==1)
down(&db)
up(&mutex);
read_data_base( );
down(&mutex);
rc=rc-1;
if(rc==0)
up(&db);
up(&mutex);
use_data_read( )
}
}
void writer (void)
{
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

39
Software Laboratory

while(TRUE)
{
think_up_data( );
down(&db);
write_data_base( );
up(&db);
}
}

Conclusion:
Implement Mutual Exclusion and Synchronization of threads using
POSIX Semaphores has been implemented.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

40
Software Laboratory

Assignment No. 11

Title of Assignment :
Linux Kernel Compilation
Problem Statement:
Linux Kernel Compilation Download a raw Linux Kernel(www.kernel.org) compile
it and boot the machine through newly compiled
Relevant Theory / Literature Survey:

Steps of Compilation

Step 1: Get Latest Linux kernel code

Visit http://kernel.org/ and download the latest source code. File name
would be linux-x.y.z.tar.bz2, where x.y.z is actual version number. For
example file inux-2.6.25.tar.bz2 represents 2.6.25 kernel version.

Use wget command to download kernel source code:

$ cd /tmp
$ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-x.y.z.tar.bz2

Note: Replace x.y.z with actual version number.

Step 2: Extract tar (.tar.bz3) file

Type the following command:


# tar -xjvf linux-2.6.25.tar.bz2 -C /usr/src
# cd /usr/src

Step 3: Configure kernel

Before you configure kernel make sure you have development tools (gcc
compilers and related tools) are installed on your system. If gcc compiler
and tools are not installed then use apt-get command under Debian
Linux to install development tools.
# apt-get install gcc

Now you can start kernel configuration by typing any one of the

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

41
Software Laboratory

command:

 $ make menuconfig - Text based color menus, radiolists & dialogs.


This option also useful on remote server if you wanna compile
kernel remotely.
 $ make xconfig - X windows (Qt) based configuration tool, works
best under KDE desktop
 $ make gconfig - X windows (Gtk) based configuration tool, works
best under Gnome Dekstop.

For example make menuconfig command launches following screen:


$ make menuconfig

You have to select different options as per your need. Each configuration
option has HELP button associated with it so select help button to get
help.

Step 4: Compile kernel

Start compiling to create a compressed kernel image, enter:


$ make
Start compiling to kernel modules:
$ make modules

Install kernel modules (become a root user, use su command):


$ su -
# make modules_install

Step 5: Install kernel

So far we have compiled kernel and installed kernel modules. It is time to


install kernel itself.
# make install

It will install three files into /boot directory as well as modification to your
kernel grub configuration file:

 System.map-2.6.25
 config-2.6.25
 vmlinuz-2.6.25
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

42
Software Laboratory

Step 6: Create an initrd image

Type the following command at a shell prompt:


# cd /boot
# mkinitrd -o initrd.img-2.6.25 2.6.25

initrd images contains device driver which needed to load rest of the
operating system later on. Not all computer requires initrd, but it is safe
to create one.

Step 7: Modify Grub configuration file - /boot/grub/menu.lst

Open file using vi:


# vi /boot/grub/menu.lst

title Debian GNU/Linux, kernel 2.6.25 Default

root (hd0,0)

kernel /boot/vmlinuz root=/dev/hdb1 ro

initrd /boot/initrd.img-2.6.25

savedefault

boot

Remember to setup correct root=/dev/hdXX device. Save and close the


file. If you think editing and writing all lines by hand is too much for you,
try out update-grub command to update the lines for each kernel in
/boot/grub/menu.lst file. Just type the command:
# update-grub

Step 8: Reboot computer and boot into your new kernel

Just issue reboot command:

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

43
Software Laboratory

# reboot

Conclusion:
Linux Kernel Compilation has been studied.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

44
Software Laboratory

Assignment 12
Title of Assignment :
System Calls
Problem Statement:
Study UNIX system calls like ps, fork, join , exec family ,wait for process
management.
Relevant Theory / Literature Survey:

ps: Process Status

ps [-eflu]

Will display, on the standard output, information about the processes


running on the system at that time.
-e
: display every process running, as well as the CPU time used by
each one.
-f
: display more information about every process running, such as
the user running it, when it started, etc.
-l
: display the long version, including the sizes of the jobs, in 4k
pages.
-u
: must be followed by a login/user name. The result will display all
processes run by user.

In the following example, the user is logged on to the console, and has no
jobs running, except for his/her shell and of course the command itself.

>ps

PID TTY TIME COMD

14304 ttyq2 0:00 ps

13943 ttyq2 0:02 tcsh

The next example shows a user using a windowing interface (in this case,
SunView):

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

45
Software Laboratory

> ps

PID TT STAT TIME COMMAND

1338 co IW 0:00 /bin/sh /home/nrccsb2/cantin/bin/sunview

1339 co IW 0:04 /usr/bin/sunview -background


/home/nrccsb2/cantin/img/space

1342 co S 3:59 textedit -Wp 479 98 -Ws 673 764 -WP 840 0 -Wi

1343 co S 0:28 clock -Wp 497 32 -Ws 210 47 -WP 704 0 -Wi -S

1345 co S 1:30 perfmeter -Wp 976 0 -Ws 170 69 -WP 0 0 -v cpu

1340 p0 D 1:34 cmdtool -Wp 0 0 -Ws 673 471 -WP 0 0 -Wl $<<$
CONSOLE $>>$

1341 p0 S 0:12 -bin/csh (csh)

1427 p0 S 0:24 perfmeter nrccsb2

1438 p0 R 0:00 ps

1347 p1 S 1:38 cmdtool -Wp 0 350 -Ws 673 550 -WP 772 0 -Wi

1348 p1 IW 0:06 -bin/csh (csh)

1351 p1 S 0:02 rlogin nrccsb2

1352 p1 S 0:02 rlogin nrccsb2

This user has many processes running, each of them taking some CPU
time. Some of the programs running are the windowing system (sunview),
textedit (a full screen ``point-and-click" editor), a clock, a performance
meter, a C shell, two windows (cmdtool), a remote logon to node nrccsb2,
and the ps program. The first column of the output is the process id, the
second column is the control terminal (co = console, p0 = ttyp0, p1 =
ttyp1), the third column is the state of the job (I = idle process, W =
swapped out, S = sleeping, D = in disk waits, R = runnable). The next

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

46
Software Laboratory

column displays the CPU time used by the process so far, in minutes:
seconds, and finally, the last column displays the command used. fork();

fork - create a new process

 SYNOPSIS

 DESCRIPTION

The fork () function creates a new process. The new process (child process)
is an exact copy of the calling process (parent process) except as detailed
below.
 The child process has a unique process ID.
 The child process ID also does not match any active process group
ID.
 The child process has a different parent process ID (that is, the
process ID of the parent process).
 The child process has its own copy of the parent's file descriptors.
Each of the child's file descriptors refers to the same open file
description with the corresponding file descriptor of the parent.
 The child process has its own copy of the parent's open directory
streams. Each open directory stream in the child process may share
directory stream positioning with the corresponding directory
stream of the parent.
 The child process may have its own copy of the parent's message
catalogue descriptors.
 The child process' values of tms_utime, tms_stime, tms_cutime and
tms_cstime are set to 0.
 The time left until an alarm clock signal is reset to 0.
 All semadj values are cleared.
 File locks set by the parent process are not inherited by the child
process.
 The set of signals pending for the child process is initialised to the
empty set.
 Interval timers are reset in the child process.
 If the Semaphores option is supported, any semaphores that are
open in the parent process will also be open in the child process.
 If the Process Memory Locking option is supported, the child
process does not inherit any address space memory locks
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

47
Software Laboratory

established by the parent process via calls to mlockall() or mlock().


 Memory mappings created in the parent are retained in the child
process. MAP_PRIVATE mappings inherited from the parent will
also be MAP_PRIVATE mappings in the child, and any modifications
to the data in these mappings made by the parent prior to calling
fork() will be visible to the child. Any modifications to the data in
MAP_PRIVATE mappings made by the parent after fork() returns will
be visible only to the parent. Modifications to the data in
MAP_PRIVATE mappings made by the child will be visible only to
the child.
 If the Process Scheduling option is supported, for the SCHED_FIFO
and SCHED_RR scheduling policies, the child process inherits the
policy and priority settings of the parent process during a fork()
function. For other scheduling policies, the policy and priority
settings on fork() are implementation-dependent.
 If the Timers option is supported, per-process timers created by the
parent are not inherited by the child process.
 If the Message Passing option is supported, the child process has
its own copy of the message queue descriptors of the parent. Each
of the message descriptors of the child refers to the same open
message queue description as the corresponding message
descriptor of the parent.
 If the Asynchronous Input and Output option is supported, no
asynchronous input or asynchronous output operations are
inherited by the child process.

The inheritance of process characteristics not defined by this document is


implementation-dependent. After fork(), both the parent and the child
processes are capable of executing independently before either one
terminates.

A process is created with a single thread. If a multi-threaded process calls


fork(), the new process contains a replica of the calling thread and its
entire address space, possibly including the states of mutexes and other
resources. Consequently, to avoid errors, the child process may only
execute async-signal safe operations until such time as one of the exec
functions is called. Fork handlers may be established by means of the
pthread_atfork() function in order to maintain application invariants
across fork() calls.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

48
Software Laboratory

join:

NAME
join - join lines of two files on a common field  

SYNOPSIS
Join [OPTION]... FILE1 FILE2  

DESCRIPTION

For each pair of input lines with identical join fields, write a line to
standard output. The default join field is the first, delimited by
whitespace. When FILE1 or FILE2 (not both) is -, read standard input.

-a SIDE
print unpairable lines coming from file SIDE
-e EMPTY
replace missing input fields with EMPTY
-i, --ignore-case ignore differences in case when comparing fields
-j FIELD
(obsolescent) equivalent to `-1 FIELD -2 FIELD'
-j1 FIELD
(obsolescent) equivalent to `-1 FIELD'
-j2 FIELD
(obsolescent) equivalent to `-2 FIELD'
-o FORMAT
obey FORMAT while constructing output line
-t CHAR
use CHAR as input and output field separator
-v SIDE
like -a SIDE, but suppress joined output lines
-1 FIELD
join on this FIELD of file 1
-2 FIELD
join on this FIELD of file 2

--help
display this help and exit
--version
output version information and exit

Unless -t CHAR is given, leading blanks separate fields and are ignored,

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

49
Software Laboratory

else fields are separated by CHAR. Any FIELD is a field number counted
from 1. FORMAT is one or more comma or blank separated specifications,
each being `SIDE.FIELD' or `0'. Default FORMAT outputs the join field,
the remaining fields from FILE1, the remaining fields from FILE2, all
separated by CHAR.  

SEE ALSO
The full documentation for join is maintained as a Texinfo manual. If the
info and join programs are properly installed at your site, the command

info join should give you access to the complete manual.

exec family:

NAME

environ, execl, execv, execle, execve, execlp, execvp - execute a file

 SYNOPSIS

#include <unistd.h>

extern char **environ;

int execl(const char *path, const char *arg0, ... /*, (char *)0 */);

int execv(const char *path, char *const argv[]);

int execle(const char *path,

const char *arg0, ... /*, (char *)0, char *const envp[]*/);

int execve(const char *path, char *const argv[], char *const envp[]);

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

50
Software Laboratory

int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);

int execvp(const char *file, char *const argv[]);

 DESCRIPTION

The exec functions replace the current process image with a new process
image. The new image is constructed from a regular, executable file called
the new process image file. There is no return from a successful exec,
because the calling process image is overlaid by the new process image.

When a C-language program is executed as a result of this call, it is


entered as a C-language function call as follows:

int main (int argc, char *argv[]);

where argc is the argument count and argv is an array of character


pointers to the arguments themselves. In addition, the following variable:

extern char **environ;

is initialised as a pointer to an array of character pointers to the


environment strings. The argv and environ arrays are each terminated by
a null pointer. The null pointer terminating the argv array is not counted
in argc.

Conforming multi-threaded applications will not use the environ variable


to access or modify any environment variable while any other thread is
concurrently modifying any environment variable. A call to any function
dependent on any environment variable is considered a use of the environ
variable to access that environment variable.

The arguments specified by a program with one of the exec functions are

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

51
Software Laboratory

passed on to the new process image in the corresponding main()


arguments.

The argument path points to a pathname that identifies the new process
image file.

The argument file is used to construct a pathname that identifies the new
process image file. If the file argument contains a slash character, the file
argument is used as the pathname for this file. Otherwise, the path prefix
for this file is obtained by a search of the directories passed as the
environment variable (see XBD specification, Environment Variables  ). If
this environment variable is not present, the results of the search are
implementation-dependent.

If the process image file is not a valid executable object, execlp() and
execvp() use the contents of that file as standard input to a command
interpreter conforming to system(). In this case, the command interpreter
becomes the new process image.

The arguments represented by arg0, ... are pointers to null-terminated


character strings. These strings constitute the argument list available to
the new process image. The list is terminated by a null pointer. The
argument arg0 should point to a filename that is associated with the
process being started by one of the exec functions.

The argument argv is an array of character pointers to null-terminated


strings. The last member of this array must be a null pointer. These
strings constitute the argument list available to the new process image.
The value in argv[0] should point to a filename that is associated with the
process being started by one of the exec functions.

The argument envp is an array of character pointers to null-terminated


strings. These strings constitute the environment for the new process
image. The envp array is terminated by a null pointer.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

52
Software Laboratory

For those forms not containing an envp pointer (.Fn execl , execv(),
execlp() and execvp()), the environment for the new process image is taken
from the external variable environ in the calling process.

The number of bytes available for the new process' combined argument
and environment lists is {ARG_MAX}. It is implementation-dependent
whether null terminators, pointers, and/or any alignment bytes are
included in this total.

File descriptors open in the calling process image remain open in the new
process image, except for those whose close-on-exec flag FD_CLOEXEC is
set. For those file descriptors that remain open, all attributes of the open
file description, including file locks remain unchanged.

Directory streams open in the calling process image are closed in the new
process image.

The state of conversion descriptors and message catalogue descriptors in


the new process image is undefined. For the new process, the equivalent
of:

setlocale(LC_ALL, "C")

is executed at startup.

Signals set to the default action (SIG_DFL) in the calling process image
are set to the default action in the new process image. Signals set to be
ignored (SIG_IGN) by the calling process image are set to be ignored by
the new process image. Signals set to be caught by the calling process
image are set to the default action in the new process image (see
<signal.h>).  After a successful call to any of the exec functions, alternate
signal stacks are not preserved and the SA_ONSTACK flag is cleared for

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

53
Software Laboratory

all signals.

After a successful call to any of the exec functions, any functions


previously registered by atexit() are no longer registered.

If the ST_NOSUID bit is set for the file system containing the new process
image file, then the effective user ID, effective group ID, saved set-user-ID
and saved set-group-ID are unchanged in the new process image.
Otherwise, if the set-user-ID mode bit of the new process image file is set,
the effective user ID of the new process image is set to the user ID of the
new process image file. Similarly, if the set-group-ID mode bit of the new
process image file is set, the effective group ID of the new process image is
set to the group ID of the new process image file. The real user ID, real
group ID, and supplementary group IDs of the new process image remain
the same as those of the calling process image. The effective user ID and
effective group ID of the new process image are saved (as the saved set-
user-ID and the saved set-group-ID for use by setuid().

Any shared memory segments attached to the calling process image will
not be attached to the new process image.

Any mappings established through mmap() are not preserved across an


exec.

If _XOPEN_REALTIME is defined and has a value other than -1, any


named semaphores open in the calling process are closed as if by
appropriate calls to sem_close().

If the Process Memory Locking option is supported, memory locks


established by the calling process via calls to mlockall() or mlock() are
removed. If locked pages in the address space of the calling process are
also mapped into the address spaces of other processes and are locked by
those processes, the locks established by the other processes will be
unaffected by the call by this process to the exec function. If the exec

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

54
Software Laboratory

function fails, the effect on memory locks is unspecified.

Memory mappings created in the process are unmapped before the


address space is rebuilt for the new process image.

If the Process Scheduling option is supported, for the SCHED_FIFO and


SCHED_RR scheduling policies, the policy and priority settings are not
changed by a call to an exec function. For other scheduling policies, the
policy and priority settings on exec are implementation-dependent.

If the Timers option is supported, per-process timers created by the


calling process are deleted before replacing the current process image
with the new process image.

If the Message Passing option is supported, all open message queue


descriptors in the calling process are closed, as described in mq_close().

If the Asynchronous Input and Output option is supported, any


outstanding asynchronous I/O operations may be canceled. Those
asynchronous I/O operations that are not canceled will complete as if the
exec function had not yet occurred, but any associated signal
notifications are suppressed. It is unspecified whether the exec function
itself blocks awaiting such I/O completion. In no event, however, will the
new process image created by the exec function be affected by the
presence of outstanding asynchronous I/O operations at the time the
exec function is called. Whether any I/O is cancelled, and which I/O may
be cancelled upon exec, is implementation-dependent.

The new process also inherits at least the following attributes from the
calling process image:

nice value (see nice())


semadj values (see semop())
process ID
parent process ID

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

55
Software Laboratory

process group ID
session membership
real user ID
real group ID
supplementary group IDs
time left until an alarm clock signal (see alarm())
current working directory
root directory
file mode creation mask (see umask())
file size limit (see ulimit())
process signal mask (see sigprocmask())
pending signal (see sigpending())
tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
resource limits
controlling terminal
interval timers

All other process attributes defined in this document will be the same in
the new and old process images. The inheritance of process attributes not
defined by this specification is implementation-dependent.

A call to any exec function from a process with more than one thread
results in all threads being terminated and the new executable image
being loaded and executed. No destructor functions will be called.

Upon successful completion, the exec functions mark for update the
st_atime field of the file. If an exec function failed but was able to locate
the process image file, whether the st_atime field is marked for update is
unspecified. Should the exec function succeed, the process image file is
considered to have been opened with open(). The corresponding close() is
considered to occur at a time after this open, but before process
termination or successful completion of a subsequent call to one of the
exec functions. The argv[] and envp[] arrays of pointers and the strings to
which those arrays point will not be modified by a call to one of the exec
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

56
Software Laboratory

functions, except as a consequence of replacing the process image.

The saved resource limits in the new process image are set to be a copy of
the process's corresponding hard and soft limits.

 RETURN VALUE

If one of the exec functions returns to the calling process image, an error
has occurred; the return value is -1, and err no is set to indicate the error.

Wait:

NAME

wait, waitpid - wait for a child process to stop or terminate

SYNOPSIS

#include <sys/wait.h>

pid_t wait(int *stat_loc);


pid_t waitpid(pid_t pid, int *stat_loc, int options);

DESCRIPTION

The wait () and waitpid() functions shall obtain status information


pertaining to one of the caller's child processes. Various options permit
status information to be obtained for child processes that have terminated
or stopped. If status information is available for two or more child
processes, the order in which their status is reported is unspecified.

The wait() function shall suspend execution of the calling thread until
status information for one of the terminated child processes of the calling
process is available, or until delivery of a signal whose action is either to
execute a signal-catching function or to terminate the process. If more
than one thread is suspended in wait () or waitpid() awaiting termination
of the same process, exactly one thread shall return the process status at
the time of the target process termination. If status information is
Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

57
Software Laboratory

available prior to the call to wait (), return shall be immediate.

The waitpid() function shall be equivalent to wait() if the pid argument is


(pid_t)-1 and the options argument is 0. Otherwise, its behavior shall be
modified by the values of the pid and options arguments.

The pid argument specifies a set of child processes for which status is
requested. The waitpid() function shall only return the status of a child
process from this set:

 If pid is equal to (pid_t)-1, status is requested for any child process.


In this respect, waitpid() is then equivalent to wait().
 If pid is greater than 0, it specifies the process ID of a single child
process for which status is requested.

 If pid is 0, status is requested for any child process whose process


group ID is equal to that of the calling process.

 If pid is less than (pid_t)-1, status is requested for any child process
whose process group ID is equal to the absolute value of pid.

The options argument is constructed from the bitwise-inclusive OR of zero


or more of the following flags, defined in the <sys/wait.h> header:

WCONTINUED
The waitpid() function shall report the status of any continued child
process specified by pid whose status has not been reported since it
continued from a job control stop.
WNOHANG
The waitpid() function shall not suspend execution of the calling
thread if status is not immediately available for one of the child
processes specified by pid.
WUNTRACED
The status of any child processes specified by pid that are stopped,
and whose status has not yet been reported since they stopped,
shall also be reported to the requesting process.

If the calling process has SA_NOCLDWAIT set or has SIGCHLD set to


SIG_IGN, and the process has no unwaited-for children that were
transformed into zombie processes, the calling thread shall block until all

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

58
Software Laboratory

of the children of the process containing the calling thread terminate, and
wait() and waitpid() shall fail and set errno to [ECHILD].

If wait() or waitpid() return because the status of a child process is


available, these functions shall return a value equal to the process ID of
the child process. In this case, if the value of the argument stat_loc is not
a null pointer, information shall be stored in the location pointed to by
stat_loc. The value stored at the location pointed to by stat_loc shall be 0
if and only if the status returned is from a terminated child process that
terminated by one of the following means:

1. The process returned 0 from main ().


2. The process called _exit() or exit() with a status argument of 0.

3. The process was terminated because the last thread in the process
terminated.

Regardless of its value, this information may be interpreted using the


following macros, which are defined in <sys/wait.h> and evaluate to
integral expressions; the stat_val argument is the integer value pointed to
by stat_loc.

WIFEXITED(stat_val)
Evaluates to a non-zero value if status was returned for a child
process that terminated normally.
WEXITSTATUS(stat_val)
If the value of WIFEXITED (stat_val) is non-zero, this macro
evaluates to the low-order 8 bits of the status argument that the
child process passed to _exit() or exit(), or the value the child
process returned from main().
WIFSIGNALED(stat_val)
Evaluates to a non-zero value if status was returned for a child
process that terminated due to the receipt of a signal that was not
caught (see <signal.h>).
WTERMSIG(stat_val)
If the value of WIFSIGNALED (stat_val) is non-zero, this macro
evaluates to the number of the signal that caused the termination
of the child process.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

59
Software Laboratory

WIFSTOPPED(stat_val)
Evaluates to a non-zero value if status was returned for a child
process that is currently stopped.
WSTOPSIG(stat_val)
If the value of WIFSTOPPED (stat_val) is non-zero, this macro
evaluates to the number of the signal that caused the child process
to stop.
WIFCONTINUED (stat_val)
Evaluates to a non-zero value if status was returned for a child
process that has continued from a job control stop. It is unspecified
whether the status value returned by calls to wait() or waitpid() for
processes created by posix_spawn() or posix_spawnp() can indicate a
WIFSTOPPED(stat_val) before subsequent calls to wait() or waitpid()
indicate WIFEXITED(stat_val) as the result of an error detected before the
new process image starts executing.
It is unspecified whether the status value returned by calls to wait() or
waitpid() for processes created by posix_spawn() or posix_spawnp() can
indicate a WIFSIGNALED(stat_val) if a signal is sent to the parent's
process group after posix_spawn() or posix_spawnp() is called.

If the information pointed to by stat_loc was stored by a call to waitpid()


that specified the WUNTRACED flag and did not specify the
WCONTINUED flag, exactly one of the macros WIFEXITED(*stat_loc),
WIFSIGNALED(*stat_loc), and WIFSTOPPED(*stat_loc) shall evaluate to a
non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid()


that specified the WUNTRACED and WCONTINUED flags, exactly one of
the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc),
WIFSTOPPED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to
a non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid()


that did not specify the WUNTRACED or WCONTINUED flags, or by a call
to the wait() function, exactly one of the macros WIFEXITED(*stat_loc) and
WIFSIGNALED(*stat_loc) shall evaluate to a non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid()


Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

60
Software Laboratory

that did not specify the WUNTRACED flag  and specified the
WCONTINUED flag, or by a call to the wait() function, exactly one of the
macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), and
WIFCONTINUED(*stat_loc) shall evaluate to a non-zero value.

If _POSIX_REALTIME_SIGNALS is defined, and the implementation


queues the SIGCHLD signal, then if wait () or waitpid() returns because
the status of a child process is available, any pending SIGCHLD signal
associated with the process ID of the child process shall be discarded.
Any other pending SIGCHLD signals shall remain pending.

Otherwise, if SIGCHLD is blocked, if wait () or waitpid() return because


the status of a child process is available, any pending SIGCHLD signal
shall be cleared unless the status of another child process is available.

For all other conditions, it is unspecified whether child status will be


available when a SIGCHLD signal is delivered.

There may be additional implementation-defined circumstances under


which wait () or waitpid() report status. This shall not occur unless the
calling process or one of its child processes explicitly makes use of a non-
standard extension. In these cases the interpretation of the reported
status is implementation-defined.

If a parent process terminates without waiting for all of its child processes
to terminate, the remaining child processes shall be assigned a new
parent process ID corresponding to an implementation-defined system
process.

RETURN VALUE

If wait () or waitpid() returns because the status of a child process is


available, these functions shall return a value equal to the process ID of
the child process for which status is reported. If wait () or waitpid()
returns due to the delivery of a signal to the calling process, -1 shall be

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

61
Software Laboratory

returned and errno set to [EINTR]. If waitpid() was invoked with


WNOHANG set in options, it has at least one child process specified by
pid for which status is not available, and status is not available for any
process specified by pid, 0 is returned. Otherwise, (pid_t)-1 shall be
returned, and errno set to indicate the error

Design Analysis/ Implementation Logic:

1. Steps followed to execute the respective command and function by


considering the example.

Conclusion:
Thus system call has been studied.

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

62
Software Laboratory

Third Year
Computer Engineering
G.H.R.C.E.M, Wagholi

63

You might also like