Sie sind auf Seite 1von 132

LAB MANUAL

CSC 409L
SYSTEM PROGRAMMING
(v. 1.0)

Student Name:
Class and Section:
Roll Number:
CGPA:
Email ID:
Submitted To:

SAIF UD DIN
SE-8(B)
5699
saifuddin.ba@gmail.com
Umar Mahmud

DEPARTMENT OF SOFTWARE ENGINEERING


Foundation University Rawalpindi Campus (FURC)
New Lalazar, Rawalpindi, Pakistan
www.fui.edu.pk
PREFACE

This lab manual has been prepared to facilitate the students of System Programming as part of Software
Engineering discipline. The manual lists experiments that are performed as part of the lab activity. The
experiments range from utilization of system services to developing processes, threads and modules.
Each experiment provides exercise question as well as question that check the knowledge and
understanding of the student. The students will be able to understand system level concepts once they
have completed this manual.

GENERAL INSTRUCTIONS
a. This is an individual based activity. Each student must have a lab manual.
b. Students are required to maintain the lab manual with them till the end of the semester.
c. All outcomes, answers to questions and illustrations must be provided in the reserved areas. If more
space is required then additional sheets may be attached.
d. It is the responsibility of the student to have the manual graded before deadlines as given by the
instructor
e. Loss of manual will result in resubmission of the complete manual.
f. Students are required to go through the experiment before coming to the lab session. Lab session
details will be given in training schedule.
g. Students must bring the manual in each lab.
h. Keep the manual neat clean and presentable.
i. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and no
resubmission will be entertained.
j. Marks will be deducted for late submission.

VERSION HISTORY
Month

Update By

February 2015

AP Umar Mahmud

CSC 409L

Details
First version created with 10 experiments

Page 2

MARKS
Exp
#

Date
Conducted

1
2
3
4
5
6
7
8
9
10

Experiment Title
FILE OPERATIONS USING
WINDOWS API
FILE SYSTEMS AND
DIRECTORY LISTINGS
WINDOWS API
PROCESSES
THREAD MANAGEMENT
VIRTUAL MACHINES
MODULE PROGRAMMING I
MODULE PROGRAMMING II
SYSTEM COMMANDS AND
REGISTRY INFORMATION
SOCKETS

10

Sessional
Mid-term Exam
Terminal Exam

10
35
50

Grand Total

CSC 409L

Max.
Marks

10
10
10
10
10
10
10
10
10

100

Page 3

Marks
Obtained

Instructor
Sign

LIST OF EXPERIMENTS
EXPERIMENT 1 FILE OPERATIONS USING WINDOWS API..........................................................4
EXPERIMENT 2 FILE SYSTEMS AND DIRECTORY LISTINGS......................................................9
EXPERIMENT 3 WINDOWS API........................................................................................................16
EXPERIMENT 4 PROCESSES.............................................................................................................21
EXPERIMENT 5 THREAD MANAGEMENT.....................................................................................29
EXPERIMENT 6 VIRTUAL MACHINE..............................................................................................34
EXPERIMENT 7 MODULE PROGRAMMING I................................................................................37
EXPERIMENT 8 MODULE PROGRAMMING II...............................................................................42
EXPERIMENT 9 SYSTEM COMMANDS AND REGISTRY INFORMATION.................................45
EXPERIMENT 10 SOCKETS...............................................................................................................57

SOFTWARE REQUIREMENTS

Platform

Software Tools

Languages

Windows 7 or 8

NetBeans 8/Eclipse Kepler

Java

Ubuntu 11

DEV++/Borland C/Visual
Studio

Intel Based Architecture

GCC

C++

VM Ware

CSC 409L

Page 4

CSC 409L

Page 5

EXPERIMENT 1 FILE OPERATIONS USING WINDOWS API


1.

Objectives:
(a). File copying with standard C library.

2.

(b). File copying with Windows API.


Time Required: 3 hrs

3.

Software Required:
(a). Visual C++/Borland C++/Dev C++
(b). Windows OS
(c). Windows System Programming Examples
Available here http://jmhartsoftware.com/WSP4_Examples.zip

4.

Computer File: A computer file is a resource for storing information, which is available to
a computer program and is usually based on some kind of durable storage. A file is
"durable" in the sense that it remains available for other programs to use after the program
that created it has finished executing. Computer files can be considered as the modern
counterpart of paper documents which traditionally are kept in office and library files, and
this is the source of the term.

5.

Creating a Random File: Create a random txt file and name it as yourname.txt. Store it in
working directory. Place any random data in this file and make its size large.

6.

File Copying with Standard C Library: Type the following code that uses C library
function: /* Chapter 1. Basic cp file copy program. C library Implementation.
Save file as copyCode.c
copyCode file1 file2: Copy file1 to file2. */
#include <stdio.h>
#include <errno.h>
#define BUF_SIZE 256
int main (int argc, char *argv [])
{
FILE *inFile, *outFile;
char rec[BUF_SIZE];
size_t bytesIn, bytesOut;
if (argc != 3) {
fprintf (stderr, "Usage of code: copyCode inputfile.txt outfile.txt\n");
return 1;
}
inFile = fopen (argv[1], "rb");

File Operations Using Windows API

Page 6

if (inFile == NULL) {
perror (argv[1]);
return 2;
}
outFile = fopen (argv[2], "wb");
if (outFile == NULL) {
perror (argv[2]);
fclose(inFile);
return 3;
}
/* Process the input file a record at a time. */
while ((bytesIn = fread (rec, 1, BUF_SIZE, inFile)) > 0) {
bytesOut = fwrite (rec, 1, bytesIn, outFile);
if (bytesOut != bytesIn) {
perror ("Fatal write error.");
fclose(inFile); fclose(outFile);
return 4;
}
}
fclose (inFile);
fclose (outFile);
return 0;
}
7.

8.

9.

Compile and execute the code in point 6. File copyCode.exe will be generated. In
Command Prompt navigate to the working directory and issue the following command
copyCode yourname.txt output.txt
What is the outcome? (Copy & paste the output screen here).

(1

What is your understanding in the above code? How is file copying carried out using C
library?

(2

File Copying with Windows API: Type the following code that uses Windows API: /* Chapter 1. Basic cp file copy program. Win32 Implementation.
Save file as copyCodeWindow.ccopyCodeWindow file1 file2: Copy file1 to file2. */
#include <windows.h>
#include <stdio.h>

File Operations Using Windows API

Page 7

#define BUF_SIZE 16384


int main (int argc, LPTSTR argv [])
{
HANDLE hIn, hOut;
DWORD nIn, nOut;
CHAR buffer [BUF_SIZE];
if (argc != 3) {
fprintf (stderr, "Usage: cp file1 file2\n");
return 1;
}
hIn = CreateFile (argv[1], GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hIn == INVALID_HANDLE_VALUE) {
fprintf (stderr, "Cannot open input file. Error: %x\n", GetLastError ());
return 2;
}
hOut = CreateFile (argv[2], GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOut == INVALID_HANDLE_VALUE) {
fprintf (stderr, "Cannot open output file. Error: %x\n", GetLastError
());
CloseHandle(hIn);
return 3;
}
while (ReadFile (hIn, buffer, BUF_SIZE, &nIn, NULL) && nIn > 0) {
WriteFile (hOut, buffer, nIn, &nOut, NULL);
if (nIn != nOut) {
fprintf (stderr, "Fatal write error: %x\n", GetLastError ());
CloseHandle(hIn); CloseHandle(hOut);
return 4;
}
}
CloseHandle (hIn);
CloseHandle (hOut);
return 0;
}
10

(1

Compile and execute the code in point 6. File copyCodeWindow.exe will be generated. In
Command Prompt navigate to the working directory and issue the following
commandcopyCodeWindow yourname.txt output.txt
What is the outcome? (Copy & paste the output screen here).

8.

What is your understanding in the above code? How is file copying carried out using C

(2

File Operations Using Windows API

Page 8

9.

library?

What is the difference of both codes?

(1
)

10
.

11
.

Now create different files of different sizes. (e.g., 2KB, 4KB, 6KB, etc). Then improve both
codes so that time could be measures i.e., time of execution of both codes. Plot a graph that
shows the effect of file size on execution time for both codes. You may select time as a
nanosecond unit. Show the graph here with atleast 10 different sizes. What is your
conclusion?

References:
http://en.wikipedia.org/wiki/Computer_file

File Operations Using Windows API

Page 9

(3
)

http://jmhartsoftware.com/WSP4_Examples.zip
12
.

Summary:
This experiment uses different codes for file copying. Two techniques are observed i.e.,
using C library and using Windows API. A graph is generated that shows the execution time
vs. size of file.

File Operations Using Windows API

Page 10

EXPERIMENT 2 FILE SYSTEMS AND DIRECTORY LISTINGS


1.

Objectives:
(a). File system information
(b). Reading file systems information in java

2.

(c). Listing files in a directory


Time Required: 3 hrs

3.

Software/Language Required:
(a). NetBeans 8/Eclipse Kepler
(b). Turbo C/Visual Studio 9/Dev C++
(c). Windows OS

4.

5.

(d). Java and C++


File Systems: In computing, a file system (or filesystem) is used to control how data is
stored and retrieved. Without a file system, information placed in a storage area would
be one large body of data with no way to tell where one piece of information stops and
the next begins. By separating the data into individual pieces, and giving each piece a
name, the information is easily separated and identified. Taking its name from the way
paper based information systems are named, each piece of data is called a "file". The
structure and logic rules used to manage the groups of information and their names is
called a "file system".
There are many different kinds of file systems. Each one has different structure and
logic, properties of speed, flexibility, security, size and more. Some file systems have
been designed to be used for specific applications. For example, the ISO 9660 file
system is designed specifically for optical disks.
File systems can be used on many different kinds of storage devices. Each storage
device uses a different kind of media. The most common storage device in use today is a
hard drive whose media is a disc that has been coated with a magnetic film. The film has
ones and zeros 'written' on it sending electrical pulses to a magnetic "read-write" head.
Other media that are used are magnetic tape, optical disc, and flash memory. In some
cases, the computer's main memory (RAM) is used to create a temporary file system for
short term use.
Partition and Volume Information: To get the file systems details type in the
following code in NetBeans.
package fileallocationtableexample;
/*
* @http://stackoverflow.com/questions/15656139/get-partition-and-volumeinformation?rq=1

File Systems and Directory Listing

Page 11

(1)

*/
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class FileAllocationTableExample {
public static void main(String[] args) {
System.out.println("File system roots
byFileSystemView.getFileSystemView():");
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++) {
System.out.println("Root: " + roots[i]);
}

returned

System.out.println("Home directory: " + fsv.getHomeDirectory());


System.out.println("File system roots returned by File.listRoots():");
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++) {
System.out.println("Drive: " + f[i]);
System.out.println("Display name: " +
fsv.getSystemDisplayName(f[i]));
System.out.println("Is drive: " + fsv.isDrive(f[i]));
System.out.println("Is floppy: " + fsv.isFloppyDrive(f[i]));
System.out.println("Readable: " + f[i].canRead());
System.out.println("Writable: " + f[i].canWrite());
System.out.println("Total space: " + f[i].getTotalSpace());
System.out.println("Usable space: " + f[i].getUsableSpace());
}
}
}
Execute the Java code and show the output here: -

File Systems and Directory Listing

Page 12

Re-execute the Java Code and connect your mobile phone as well as USB devices with
your system. Also insert a DVD/CD in the ROM. Display output here: -

6.

What is the difference in the above outputs? What kind of information was shared?

(1)

7.

FileSystems Class: import the org.openide.filesystems.FileSystem classin a java code


and execute the getDefault() function as shown below

(1)

File Systems and Directory Listing

Page 13

package fileallocationtableexample;
import java.nio.file.FileSystems;
/**
*@http://bits.netbeans.org/dev/javadoc/org-openidefilesystems/org/openide/filesystems/FileSystem.html
*/
public class TestFileSystem {
public static void main(String args[]){
System.out.println(FileSystems.getDefault());
}
}
What is the output? Show here? What did you understand by the code?

8.

File Roots: Execute the following code to display the roots.


package fileallocationtableexample;
/**
* @http://www.tutorialspoint.com/java/io/file_listroots.htm
*/
import java.io.File;
public class FileRoots {
public static void main(String[] args) {
File[] paths;
try{
// returns pathnames for files and directory
paths = File.listRoots();
// for each pathname in pathname array
for(File path:paths)
{
// prints file and directory paths
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
What is the output? Show here: -

File Systems and Directory Listing

Page 14

(1)

9.

Directory: In computing, a directory is a file system cataloguing structure which


contains references to other computer files, and possibly other directories. On many
computers directories are known as folders, catalogues (used on the Apple II, the
Commodore 128 and some other early home computers as a command for displaying
disk contents - the file systems used by these DOS did not support hierarchal
directories), or drawersto provide some relevancy to a workbench or the traditional
office file cabinet. On Microsoft Windows, the terms folder and directory are used
interchangeably. Files are organized by storing related files in the same directory. In a
hierarchical file system (that is, one in which files and directories are organized in a
manner that resembles a tree), a directory contained inside another directory is called a
subdirectory. The terms parent and child are often used to describe the relationship
between a subdirectory and the directory in which it is catalogued, the latter being the
parent. The top-most directory in such a files system, which does not have a parent of its
own, is called the root directory. Following figure shows a directory listing:

10.

Directory Listing Using C/C++:The following code gives the directory listing using
C++.
#include <fstream>
#include <iostream>
#include <string>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
int main()
{
ifstream fin;
string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;
cout << "dir to get files of: " << flush;
getline( cin, dir ); // gets everything the user ENTERs
dp = opendir( dir.c_str() );
if (dp == NULL)

File Systems and Directory Listing

Page 15

(1)

{
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir( dp )))
{
filepath = dir + "/" + dirp->d_name;
// If the file is a directory (or is in some way invalid) we'll skip it
if (stat( filepath.c_str(), &filestat )) continue;
if (S_ISDIR( filestat.st_mode ))
continue;
// read a single number from the file and display it
fin.open( filepath.c_str() );
if (fin >> num)
cout << filepath << ": " << num << endl;
fin.close();
}
closedir( dp );
return 0;
}
Execute this code and show the output here: -

11.

Directory Listing in Java: The following code shows the directory listing of working
directory.
package test;
import java.io.File;
public class ListFiles {
public static void main(String[] args) {
// Directory path here
String path = "."; //path name here
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
}

File Systems and Directory Listing

Page 16

Execute this code and show the output here: -

12.

Update both codes that shows the directory listing of a given directory in a column
format showing the File Name, File Size, and File Rights (Read only, Write Only, Both)
and Last Accessed Time and date. Show the output of both codes here and show the
execution on machine as well.

13.

References:
http://stackoverflow.com/questions/15656139/get-partition-and-volume-information?
rq=1http://en.wikipedia.org/wiki/File_system
http://bits.netbeans.org/dev/javadoc/org-openidefilesystems/org/openide/filesystems/FileSystem.html
http://www.tutorialspoint.com/java/io/file_listroots.htm
https://en.wikipedia.org/wiki/Directory_%28computing%29
https://en.wikipedia.org/wiki/File:DirectoryListing1.png
http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-programcan-list-all-files-given-directory.html
http://www.cplusplus.com/forum/beginner/10292/

12.

Summary: This experiment uses different methods available in Java to access File
System Descriptions and Roots information. Furthermore, directory listing using Java
and C++ is also observed. Students are required to update both codes so that complete
directory listing is achieved.

File Systems and Directory Listing

Page 17

(3)

EXPERIMENT 3 WINDOWS API


1.

2.
3.
4.

5.

Objectives:
(a). Windows API
(b). WinMain()
(c). Message Loop
Time Required: 3 hrs
Software/Language Required:
(a). Turbo C/Visual Studio 9/Dev C++
(b). Windows OS
Win 32 API: The Windows API, informally WinAPI, is Microsoft's core set of application
programming interfaces (APIs) available in the Microsoft Windows operating systems. The
name Windows API collectively refers to a number of different platform implementations
that are often referred to by their own names (for example, Win32 API). Almost all
Windows programs interact with the Windows API.The Windows API (Win32) is
implemented in the C programming language and is not object-oriented. Windows 8, while
still providing the Win32 API, also provides the WinRT API which is implemented in the
C++ programming languageand is object-oriented by its design.
Directory Listing Using C/C++: Type in the following code.

(1
)

Ex
ecute this code and show the output here: -

WinMain() is windows equivalent of main() from DOS. This is where your program starts
execution. The parameters are as follows:
HINSTANCE hInstance. Handle to the programs executable module (the .exe file in
memory). It is is used for things like loading resources and any other task which is
performed on a per-module basis. A module is either the EXE or a DLL loaded into your
program.
HINSTANCE hPrevInstance. Always NULL for Win32 programs. It used to be the handle
Windows API

Page 18

6.

to the previously run instance of your program (if any) in Win16. This no longer applies. In
Win32 you ignore this parameter.
LPSTR lpCmdLine. The command line arguments as a single string. NOT including the
program name.
int nCmdShow. An integer value which may be passed to ShowWindow().
Simple Window Program: Type the following code
#include <windows.h>
const char g_szClassName[] = "myWindowClass";
// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
//Step 1: Registering the Window Class
wc.cbSize
= sizeof(WNDCLASSEX);
wc.style
= 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon
= LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor
= LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm
= LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// Step 2: Creating the Window
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,

Windows API

Page 19

(1
)

g_szClassName,
"The title of my window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 3: The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
Execute this code and show the output here: -

7.

Step 1 - Registering Window Class: A Window Class stores information about a type of
window, including its Window Procedure which controls the window, the small and large
icons for the window, and the background color. This way, you can register a class once, and
create as many windows as you want from it, without having to specify all those attributes
over and over. Most of the attributes you set in the window class can be changed on a perwindow basis if desired. A Window Class has NOTHING to do with C++ classes.
Step 2 - Creating The Window: Once the class is registered, we can create a window with
it.
Step 3 Message Loop: This is the heart of the whole program, pretty much everything
that your program does passes through this point of control.GetMessage() gets a message
from your application's message queue. Any time the user moves the mouse, types on the
keyboard, clicks on your window's menu, messages are generated by the system and entered
into your program's message queue. By calling GetMessage() you are requesting the next
available message to be removed from the queue and returned to you for processing. If there
is no message, GetMessage() Blocks. TranslateMessage() does some additional processing

Windows API

Page 20

8.

on keyboard events like generating WM_CHAR messages to go along with


WM_KEYDOWN messages. Finally DispatchMessage() sends the message out to the
window that the message was sent to. This could be our main window or it could be another
one, or a control, and in some cases a window that was created behind the scenes by the
system or another program.
Step 4 Window Procedure: If the message loop is the heart of the program, the window
procedure is the brain. This is where all the messages that are sent to our window get
processed.The window procedure is called for each message, the HWND parameter is the
handle of your window, the one that the message applies to. This is important since you
might have two or more windows of the same class and they will use the same window
procedure (WndProc()). The difference is that the parameter HWND will be different
depending on which window it is. For example when we get the WM_CLOSE message we
destroy the window.
Adding Further Functionality to Windows Procedure: Add the following code in Step 4
(Switch Statement).
case WM_LBUTTONDOWN:
{
char szFileName[MAX_PATH];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, szFileName, MAX_PATH);
MessageBox(hwnd, szFileName, "This program is:", MB_OK |
MB_ICONINFORMATION);
}
Execute this code and show the output here: -

(2
)

What did the code do?

9.

Update the code so as that it prints the file parameters of the executable including file name,

Windows API

Page 21

(6

file size and creation date in the dialog box. Show code and output here

Windows API

Page 22

10
.

11
.

References:
http://www.winprog.org/tutorial/simple_window.html
https://en.wikipedia.org/wiki/Windows_API
http://msdn.microsoft.com/en-us/library/ff818516%28v=vs.85%29.aspx
Summary: This experiment provides examples to create a window using Win API. The use
of WinMain(), Message Loop and WinProcedure() are observed.

Windows API

Page 23

EXPERIMENT 4 PROCESSES
1.

Objectives:
(a). Creating processes in Ubuntu.
(b). Learning fork commands in Ubuntu

2.

Time Required: 3 hrs

3.

Software Required:
(a). Ubuntu/Linux and gcc compiler (already available in Ubuntu)
(b). Borland/Turbo C/Visual Studio for Windows Platform
(c). VMWare if required
(d). C language

4.

How to compile C Program in Ubuntu/Linux


(a). Save your program with extension .c in any directory (working directory).
(b). Open Terminal.
(c). Navigate to the working directory
(d). Suppose you saved the program with name hello.c. Now write following lines:
gcc -c hello.c
gcc -o hello hello.c
./hello
(e). The first line compiles your program. Object file hello.o is created
(f). Second line makes an exe file with the name hello.

Processes

Page 24

(g). Third line runs the exe file and shows output of the program.
5.

Using getpid(): This function returns the pid of the current program. Use the following code and
write the output.
int main(){
int pid;
pid = getpid();
printf(Process ID is %d\n, pid);
return 0;
}

6.

What is the outcome of the following program?


int main(){
long i;

Processes

Page 25

printf(Process ID is %d\n, getpid());


for(i=0; i<=400;i++)
{
printf(i is %d\n, i);
}
return 0;
}

Outcome:

waqar@ubunte:~Desktop$ ./hello

Process Id is 4739
I is 0 . I is 399

7.

Using getppid(): This function returns the pid of the parent process.
int main(){

Processes

Page 26

int ppid;
ppid = getppid();
printf(Parent Process ID is %d\n, ppid);
return 0;
}
What is the outcome?

8.

Using fork(): fork command in Linux creates a new process by duplicating the calling process. The
new process, referred to as the child, is an exact duplicate of the calling process, referred to as the
parent.What is the outcome of the following program?
int main(){
fork();

Processes

Page 27

printf(The PID is %d\n, getpid());


return 0;
}

9.

What is the outcome of the following program?


int main(){
int pid;
pid = fork();
if(pid==0){
printf(I am the child, my process ID is %d\n, getpid());
printf(The childs parent process ID is %d\n, getppid());
}

Processes

Page 28

else{
printf(I am the parent, my process ID is %d\n, getpid());
printf(The parent process ID is %d\n, getppid());
}
return 0;
}

10. To see if the pid is same as shown in the system, Open System Monitor. Check to see if the pid is
same. Use the following code
int main(){
int pid,i;
pid = fork();
if(pid==0){
Processes

Page 29

printf(I am the child, my process ID is %d\n, getpid());


printf(The childs parent process ID is %d\n, getppid());
}
else{
printf(I am the parent, my process ID is %d\n, getpid());
printf(The parent process ID is %d\n, getppid());
}
scanf(%d,&i); //so that program halts for user input
return 0;
}

11. What do you understand from points 8, 9 and 10?


Processes

Page 30

(3)

12. What is the outcome of this program?


/**
* This program forks a separate process using the fork()/exec() system calls.
* * Figure 3.10*
* @author Gagne, Galvin, Silberschatz Operating System Concepts - Seventh Edition
* Copyright John Wiley & Sons - 2005. */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
Processes

Page 31

int main(){
pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid == 0) { /* child process */
printf("I am the child %d\n",pid);
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
printf("I am the parent %d\n",pid);
wait(NULL);

printf("Child Complete\n");
exit(0);
}
Processes

Page 32

13. Explain how was the execution carried out in program in point 11? You may use a flow model to (3)
describe it.

Processes

Page 33

14. Using Exec: The fork system call creates a new process but that process contains, and is executing,
exactly the same code that the parent process has. More often than not, we'd like to run a new
program.
15. Example of Execve():The execve system call replaces the current process with a new program.Type
the following command in Terminal and show the output.
ls -aF /
Now execute the following code
/* execve: run a program */
#include <stdlib.h>

/* needed to define exit() */

#include <unistd.h>

/* needed to define getpid() */

#include <stdio.h>

/* needed for printf() */

Processes

Page 34

intmain(int argc, char **argv) {


char *args[] = {"ls", "-aF", "/", 0}; /* each element represents a command line
argument */
char *env[] = { 0 };

/* leave the environment list null */

printf("About to run /bin/ls\n");


execve("/bin/ls", args, env);
perror("execve");

/* if we get here, execve failed */

exit(1);
}
What is the outcome?

Processes

Page 35

16. Using Execlp


execlp, which allows you to specify all the arguments as parameters to the function. Note that the first
parameter is the command. The second parameter is the first argument in the argument list that is
passed to the program (argv[0]). These are often the same but don't have to be. The last parameter
must be a null pointer.
/* execlp: run a program using execlp */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed to define getpid() */
#include <stdio.h>
/* needed for printf() */
int main(int argc, char **argv) {
printf("About to run ls\n");
execlp("ls", "ls", "-aF", "/", (char*)0);
perror("execlp");/* if we get here, execlp failed */
exit(1);
}
What is the output?

17. Using fork() and exec(): The fork system call creates a new process. The execve system call
overwrites a process with a new program. A process forks itself and the child process execs a new
program, which overlays the one in the current process.
/* forkexec: create a new process. */
/* The child runs "ls -aF /". The parent wakes up after 5 seconds */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed for fork() and getpid() */
#include <stdio.h>
/* needed for printf() */
Int main(int argc, char **argv) {
void runit(void);
int pid; /* process ID */
switch (pid = fork()) {
case 0:
/* a fork returns 0 to the child */
runit();
break;
default: /* a fork returns a pid to the parent */
sleep(5); /* sleep for 5 seconds */
Processes

Page 36

printf("I'm still here!\n");


break;
case -1: /* something went wrong */
perror("fork");
exit(1);
}
exit(0);
}
void runit(void) {
printf("About to run ls\n");
execlp("ls", "ls", "-aF", "/", (char*)0);
perror("execlp");/* if we get here, execlp failed */
exit(1);
}
What is the outcome of the program?

18. What do you understand from point 17?

Processes

(3)

Page 37

19. Creating a Process in Windows:


/**
* This program creates a separate process using the CreateProcess() system call. Figure 3.12
* @author Gagne, Galvin, Silberschatz Operating System Concepts - Seventh Edition
* Copyright John Wiley & Sons - 2005.
*/
#include <windows.h>
#include <stdio.h>
int main( VOID ){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi) );// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line).
"C:\\WINDOWS\\system32\\mspaint.exe", // Command line.
NULL,

// Process handle not inheritable.

NULL,

// Thread handle not inheritable.

FALSE,

// Set handle inheritance to FALSE.

0,
Processes

// No creation flags.
Page 38

NULL,

// Use parent's environment block.

NULL,

// Use parent's starting directory.

&si,

// Pointer to STARTUPINFO structure.

&pi )

// Pointer to PROCESS_INFORMATION structure.

)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return -1;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
What is the Outcome?

Processes

Page 39

20. Which OS gives you a better interface for creating and executing child programs and why?

Processes

Page 40

(1)

21. Reference Material/Web Resources


http://manpages.ubuntu.com/manpages/lucid/man2/fork.2.html
Processes

Page 41

http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/exec.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/forkexec.html
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch03-processes.pdf
22. Summary: This experiment allows the students to work processes in Ubuntu using fork() command.
Code for process creation in windows is also given. The use of Exec() is also observed.

Processes

Page 42

EXPERIMENT 5 THREAD MANAGEMENT

1.

Objectives:
(a). Using Java Threads
(b). Thread Synchronization

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java
(b). Windows/Ubuntu

4.

Multithreading: Multithreading refers to two or more tasks executing concurrently within


a single program. A thread is an independent path of execution within a program. Many
threads can run concurrently within a program.

5.

Context Switch Using Threads: Switching among threads is much cheaper than to
switch processes as threads share the same process area.

6.

Java Threads; Every thread in Java is created and controlled by the java.lang.Thread
class. A Java program can have many threads, and these threads can run concurrently,
either asynchronously or synchronously. Following shows the methods in Object and
Thread Classes of Java.

7.

Thread Creation by Implementing The Runnable Interface:


public interface Runnable {
void run();

Thread Management

Page 43

}
One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class
which is the only method that needs to be implemented. The run() method contains the
logic of the thread.
(a). A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
(b). An object of Thread class is created by passing a Runnable object as argument to
the Thread constructor. The Thread object now has a Runnable object that
implements the run() method.
(c). The start() method is invoked on the Thread object created in the previous step.
The start() method returns immediately after a thread has been spawned.
(d). The thread ends when the run() method ends, either by normal completion or by
throwing an uncaught exception.
8.

Thread Creation by Extending the Thread Class: The procedure for creating threads
based on extending the Thread is as follows:
(a). A class extending the Thread class overrides the run() method from the Thread
class to define the code executed by the thread.
(b). This subclass may call a Thread constructor explicitly in its constructors to
initialize the thread, using the super() call.
(c). The start() method inherited from the Thread class is invoked on the object of the
class to make the thread eligible for running.

9.

Type in the following code. Execute and show outcome:


/**
* @(#)ThreadExample.java
* @author Engr. Umar Mahmud

Thread Management

Page 44

(1)

* @version 1.00 2014/4/25


*/
public class ThreadExample extends Thread { //To create producer and consumer
as threads
public ThreadExample(String threadName){
super(threadName);

//Constuctor
//Call to constructor of Thread class

}
public void run(){
System.out.println("I
am
a
thread
"+Thread.currentThread().getName());

and

my

name

is

}
public static void main(String[] args) {
ThreadExample t = new ThreadExample("Thread 01"); //Create a thread
object
t.start();

//execute run() method

OutCome:

Thread Management

Page 45

10.

Create another thread object and execute it. Show code and outcome here:

Thread Management

Page 46

(1)

11.

Execute the following code for producer and consumer. Execute and show outcome:
/**
* @(#)ProducerConsumerUsingThreads.java
* ProducerConsumerUsingThreads application
* @author Engr. Umar Mahmud
* @version 1.00 2013/12/20
*/
public class ProducerConsumerUsingThreads extends Thread {
//To create producer and consumer as threads
private int x = 0;
//Shared variable
private int maxLimit = 5;
//Maximum Limit to simulate a buffer
public ProducerConsumerUsingThreads(String threadName){
//Constuctor
super(threadName);

Thread Management

//Call to constructor of Thread class


Page 47

(1)

}
public void run(){
for(int i = 0; i< 10; i++){
System.out.println(Thread.currentThread().getName());
if(Thread.currentThread().getName().startsWith("Producer")){
//In a producer
if(x<maxLimit){
x++;
}
else{
System.out.println("\nProducer blocked");
yield();
//Give way to another thread
}
}
else
if(Thread.currentThread().getName().startsWith("Consumer")){
//In a Consumer
if(x>0){
x--;
Thread Management

Page 48

}
else{
System.out.println("\nConsumer blocked");
yield();
//Give way to another thread
}
}
else{
//default case
System.out.println("Some Error");
}
}
}
public static void main(String[] args) {
ProducerConsumerUsingThreads
p
ProducerConsumerUsingThreads("Producer");

new

ProducerConsumerUsingThreads
c
ProducerConsumerUsingThreads("Consumer");

new

p.start();
c.start();

Thread Management

Page 49

Re-execute the code and identify if the output trace is same as before.

Thread Management

Page 50

Again re-execute the code and identify if the output trace is same as before.

Thread Management

Page 51

12.

What happened in the code in Point 12?

Thread Management

Page 52

(2)

13.

Create two threads one to read from a file and the other to write into another file. Show
the output and code for a given text file.

/* @(#)ThreadExample.java
* @author Engr. Umar Mahmud
* @version 1.00 2014/4/25
*/import java.io.*;
import java.util.Scanner;
public class exp512 extends Thread {
threads
public exp512(String threadName){
super(threadName);
Thread class
}
String path = "E:\\waqar.txt";
public void run(){

Thread Management

Page 53

//To create producer and consumer as

//Constuctor
//Call to constructor of

(5)

if(Thread.currentThread().getName().equals("Read"))
readFromFile();
else if(Thread.currentThread().getName().equals("Write"))
writeToFile();
else
System.out.println("Apologies! Thread got confused");
}
public static void main(String[] args) throws IOException {
exp512 readThread = new exp512("Read");
exp512 writeThread = new exp512("Write");
//

Create a thread object


readThread.start();
writeThread.start(); //execute run() method

public void readFromFile(){


int i = 0;
FileInputStream fin;

Thread Management

Page 54

try {
fin = new FileInputStream(path);

} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {

try {
i = fin.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread Management

Page 55

if(i != -1) System.out.print((char) i);


} while(i != -1);
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

public void writeToFile(){


try {

//= "Zrurat khatam";


System.out.println("Enter new content for the file: ");
Scanner input = new Scanner(System.in);
String content = input.nextLine();
Thread Management

Page 56

File file = new File(path);

// if file doesn't exists, then create it


if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());


BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();

} catch (IOException e) {
e.printStackTrace();
}
}

Thread Management

Page 57

OutPut:

14.

References
http://www.youtube.com/watch?v=KxTRsvgqoVQ
http://www.youtube.com/watch?v=D0u2USIonds
http://www.youtube.com/watch?v=CKFq-WTZZc8
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html [MUST VISIT]
http://www.javabeginner.com/learn-java/java-threads-tutorial

15.

Summary: This experiment allows the students to work with threads and see how thread
switching works. Students work with examples to solve producer consumer as well as
reader writer problem using threads

Thread Management

Page 58

EXPERIMENT 6 VIRTUAL MACHINE

1.

Objectives:
(a). Using VM Ware
(b). Loading Ubuntu on VM Ware
(c). Working with system tools in Linux as well as Windows while using VM Ware

2.

Time Required: 3 hrs

3.

Software/Language Required:
(a). VM Ware
(b). Windows OS/Ubuntu 10

4.

VM Ware: VMware, Inc. is an American software company that provides cloud and
virtualization software and services and was the first to successfully virtualize the x86
architecture. VMware's desktop software runs on Microsoft Windows, Linux, and Mac OS
X, while its enterprise software hypervisors for servers, VMware ESX and VMware ESXi,
are bare-metal hypervisors that run directly on server hardware without requiring an
additional underlying operating system.

5.

Hypervisor: A hypervisor or virtual machine monitor (VMM) is a piece of computer


software, firmware or hardware that creates and runs virtual machines.A computer on
which a hypervisor is running one or more virtual machines is defined as a host machine.
Each virtual machine is called a guest machine. The hypervisor presents the guest
operating systems with a virtual operating platform and manages the execution of the
guest operating systems. Multiple instances of a variety of operating systems may share
the virtualized hardware resources.

6.

Installing VM Ware: Install VMWare (if not installed already on your machine). Install
Ubuntu on WM Ware.

7.

See the Task manager in windows and identify if the VM Ware is shown as a
service/process? Show its attributes here:

Virtual Machines

Page 59

(3)

Based on the attributes information, where does VM Ware reside? i.e., on Windows or on
hardware? Give reasons

8.

Open Terminal in Ubuntu as part of VM Ware. Type the commandifconfig. What is the
output? Show here

Virtual Machines

Page 60

(1)

9.

Open command prompt in Windows. Typeipconfig. What is the output? Show here.

Virtual Machines

Page 61

(1)

10.

What is your conclusion from points 8 and 9?

Virtual Machines

Page 62

(3)

11.

Write a C++ program that creates an array of 200 integers, and iteratively squares each
element of that array. Execute the code and observe Task manager as well as system
monitor (in Ubuntu) simultaneously. Looking at the CPU load what is your observation?

Virtual Machines

Page 63

(2)

12.

References:
https://www.vmware.com/pdf/ws6_manual.pdf
https://www.vmware.com/support/ws55/doc/ws_newguest_setup_simple_steps.html
https://en.wikipedia.org/wiki/VMware
http://www.youtube.com/watch?v=z2aVFqp0oc8
https://en.wikipedia.org/wiki/Hypervisor

13.

Summary: This experiment allows the students to work with VM Ware and load a
different OS on it. The students are also able to observe different parameters both in Linux
as well Windows using VM Ware and draw appropriate conclusions.

Virtual Machines

Page 64

EXPERIMENT 7 MODULE PROGRAMMING I

1. Objectives:
(a). Module programming
(b). Developing modules in Ubuntu
(c). Hello World module in Ubuntu
2. Time Required: 3 hrs
3. Software Required:
(a). gcc compiler
(b). C language
(c). Ubuntu
4. Modules: In computing, a loadable kernel module (or LKM) is an object file that contains
code to extend the running kernel, or so-called base kernel, of an operating system. LKMs are
typically used to add support for new hardware, file-systems, or for adding system calls.
When the functionality provided by an LKM is no longer required, it can be unloaded in
order to free memory and other resources.
Modules are programs that execute in the OS shell or Ring 0.
5. Creating Hello World Module: In this experiment the simplest hello world module will be
created. The steps are as follows: -

(
1
)

(a).

Make a folder on the desktop for this lab. Make sure that the name of the folder does
not have a space character in it. Write the name of the folder here saifisystem_____.

(b).

Create a text file using a text editor with the name hello-1.c. You may create any file
name but the extension should be .c.

(c).

Write the following code in the text file. Text file is edited using the Text Edit tool in
Linux

Module Programming I

Page 65

#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
int init_module(void){
printk(KERN_INFO "Sky Fall\n");
// A non 0 return means init_module failed
// module can't be loaded.
return 0;
}
void cleanup_module(void){
printk(KERN_INFO "Breaking Dawn.\n");
}

(d).

Do not compile the code as yet.

(e).

Kernel modules must have at least two functions: a "start" (initialization) function
called init_module() which is called when the module is loaded (insmod) into the
kernel, and an "end" (cleanup) function called cleanup_module() which is called just
before it is removed (rmmod).

(f).

printk() is not meant to communicate information to the user. It happens to be a


logging mechanism for the kernel, and is used to log information or give warnings. To
view the log system log has to be seen.

(g).

Open terminal and navigate to the working directory

(h).

Type lsmod to list the modules loaded in the kernel.

6. Compiling Hello World Module: Now the module will be compiled by creating a make file.
The steps are as under: -

(
3
)

(a). Create a new file using the text editor and store it with the name Makefile in the
working directory. Do not use any extensions while storing the file.

Module Programming I

Page 66

(b). Type the following commands in the Makefile


obj-m += hello-1.o
all:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd)

modules
clean:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

(c). The first line should show the name of your file with .o extension after the +=
characters.
(d). Do not forget to put a tab character before make in both instances of the keyword
make.
(e). In the terminal type sudo make. If asked for the password type in the password.
(f). What is the outcome of this step (if correctly executed)? Show the output as well as
the names of the files created in the working directory.

Module Programming I

Page 67

(g). Use modinfo hello-1.ko to see what kind of information it is. Show the output here.

Module Programming I

Page 68

7. Loading Module: To load the module in kernel type sudo insmod ./hello-1.ko andremember
to rename hello-1 if you have different file name.
8. Type lsmod and see if the module is loaded. Show the screen capture here.

(
1
)

Module Programming I

Page 69

9. Viewing Log: To view log type dmesg. Show the output here.

(
1
)

Module Programming I

Page 70

Removing Modules: To remove module type sudo rmmod hello-1 andremember to rename
0. hello-1 if you have different file name.
1

Type lsmod and see if the module is unloaded.

1.

Module Programming I

Page 71

Type dmesg again and show the output here.

2.

(
1
)

Module Programming I

Page 72

1
3.

Hello World Improved: Write the following code in a new file. Name the file hello-2.c
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
#include <linux/init.h>
/* Needed for the macros */
static int __init hello_2_init(void){
printk(KERN_INFO "Hello, world 2\n");
return 0;
}
static void __exit hello_2_exit(void){
printk(KERN_INFO "Goodbye, world 2\n");
}
module_init(hello_2_init);
module_exit(hello_2_exit);

Module Programming I

Page 73

Remember that there are two underscores before init and exit keywords
1
4.

Modify the make file as follows:


obj-m += hello-1.o
obj-m += hello-2.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

Type sudo make to compile new module

5.
1

Check the module directory by typing lsmod

6.
1

Insert modules by typing sudo insmod ./hello-1.ko and sudo insmod ./hello-2.ko
7. andremember to rename filenames if you have different file name
Module Programming I

Page 74

Check the log by typing dmesg. Show the output here.

8.

(
1
)

Module Programming I

Page 75

Remove the modules by typing sudo rmmod hello-1 and then sudo rmmod hello-2

9.
2

Show the output of dmesg

0.

1
)

Module Programming I

Page 76

Init data: The __init macro causes the init function to be discarded and its memory freed
1. once the initfunction finishes for builtin drivers, but not loadable modules. If you think
about when the init function isinvoked, this makes perfect sense.There is also an __initdata
which works similarly to __init but for init variables rather than functions.
Type the following code and name it hello-3.c
Module Programming I

Page 77

(
1
)

Load the module and show output here:

Module Programming I

Page 78

What did you learn in this experiment?

2.

Module Programming I

Page 79

Module Programming I

Page 80

Resources:

3.
https://en.wikipedia.org/wiki/Loadable_kernel_module
www.tldp.org/LDP/lkmpg/2.6/lkmpg.pdf
http://www.tldp.org/LDP/lkmpg/2.6/html/index.html
2

Summary:

This experiment introduces module programming in Linux/Ubuntu where

Module Programming I

Page 81

4. students are required to create simple hello world modules. The loading and removal is also
observed.

Module Programming I

Page 82

EXPERIMENT 8 MODULE PROGRAMMING II


1.

Objectives:
(a). Module Programming in Linux
(b). Licencing and command line arguments in modules

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu

4.

License Information: In kernel 2.4 and later, a mechanism was devised to identify code
licensed under the GPL (and friends) so people can be warned that the code is non opensource. This is accomplished by the MODULE_LICENSE() macro which is demonstrated
in the next piece of code. By setting the license to GPL, you can keep the warning from
being printed.

5.

Information Macros: MODULE_DESCRIPTION() is used to describe what the module


does,
MODULE_AUTHOR()
declares
the
module's
author,
and
MODULE_SUPPORTED_DEVICE() declares what types of devices the module supports.

6.

Create
the following
module and name
as hello-4.c
* hello-4.c
- Demonstrates
module
documentation.

/*

*/
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
#include <linux/init.h>
/* Needed for the macros */
#define DRIVER_AUTHOR "Type your name and email here
#define DRIVER_DESC
"Give the description of your driver"
static int __init init_hello_4(void)
{
printk(KERN_INFO "Hello, world 4\n");
return 0;
}
static void __exit cleanup_hello_4(void)
{
printk(KERN_INFO "Goodbye, world 4\n");
}
module_init(init_hello_4);
module_exit(cleanup_hello_4);
MODULE_LICENSE("GPL");
MODULE_AUTHOR(DRIVER_AUTHOR); /* Who wrote this module? */
MODULE_DESCRIPTION(DRIVER_DESC); /* What does this module do */
MODULE_SUPPORTED_DEVICE("testdevice");

Module Programming II

Page 83

7.

Load the module and show the outcome here:

Module Programming II

Page 84

Module Programming II

Page 85

8.

Passing Command Line Arguments to Modules: Modules can take command line
arguments, but not with the argc/argv you might be used to.To allow arguments to be
passed to your module, declare the variables that will take the values of the command line
arguments as global and then use the module_param() macro, (defined in
linux/moduleparam.h) to set the mechanism up. At runtime, insmod will fill the variables
with any command line arguments that are given, like ./insmod mymodule.ko
myvariable=5. The variable declarations and macros should be placed at the beginning of
the module for clarity. The example code should clear up my admittedly lousy explanation.
The module_param() macro takes 3 arguments: the name of the variable, its type and
permissions for the corresponding file in sysfs. Integer types can be signed as usual or
unsigned.
int myint = 3;
module_param(myint, int, 0);

9.

Type the following code and save as hello-5.c


/*/*
** module_param_array(name,
num,line
perm);
hello-5.c - Demonstratestype,
command
argument passing to a module.
* */
The first param is the parameter's (in this case the array's) name
*#include
The second
param is the data type of the elements of the array
<linux/module.h>
*#include
The third
argument is a pointer to the variable that will store the
<linux/moduleparam.h>
number
#include <linux/kernel.h>
*#include
of elements
of the array initialized by the user at module loading
<linux/init.h>
time
#include <linux/stat.h>
*MODULE_LICENSE("GPL");
The fourth argument is the permission bits
*/
MODULE_AUTHOR("YOUR NAME");
module_param_array(myintArray, int, &arr_argc, 0000);
MODULE_PARM_DESC(myintArray,
"An array of integers");
static short int myshort = 1;
static int myint = 420;
static
__init
hello_5_init(void)
staticint
long
int mylong
= 9999;
{ static char *mystring = "furc";
static int
int i;
myintArray[2] = { -1, -1 };
static printk(KERN_INFO
int arr_argc = 0;"Hello, world 5\n=============\n");
printk(KERN_INFO "myshort is a short integer: %hd\n",
myshort);
/*
printk(KERN_INFO
"myint
* module_param(foo,
int,
0000)is an integer: %d\n", myint);
printk(KERN_INFO
"mylong
is a long
* The first param is the parameters
name integer: %ld\n", mylong);
"mystring
is a string: %s\n", mystring);
* The printk(KERN_INFO
second param is it's
data type
(i argument
= 0; i < is
(sizeof
myintArray bits,
/ sizeof (int)); i++)
* The for
final
the permissions
* for {exposing parameters in sysfs (if non-zero) at a later stage.
printk(KERN_INFO "myintArray[%d] = %d\n", i,
*/
myintArray[i]);
}
module_param(myshort,
short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
printk(KERN_INFO "got
arguments
for myintArray.\n",
MODULE_PARM_DESC(myshort,
"A %d
short
integer");
arr_argc);
module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
return 0;
MODULE_PARM_DESC(myint,
"An integer");
} module_param(mylong, long, S_IRUSR);
MODULE_PARM_DESC(mylong, "A long integer");
static
void __exit hello_5_exit(void)
module_param(mystring,
charp, 0000);
{ MODULE_PARM_DESC(mystring, "A character string");
printk(KERN_INFO "Goodbye, world 5\n");
} /*
module_init(hello_5_init);
module_exit(hello_5_exit);

Module Programming II

Page 86

Module Programming II

Page 87

10.

Module Programming II

Page 88

Module Programming II

Page 89

11.

Load the module using the following command


sudo insmod hello-5.ko myintArray=1,4
What is the outcome?

Module Programming II

Page 90

12.

References:
https://en.wikipedia.org/wiki/Loadable_kernel_module
www.tldp.org/LDP/lkmpg/2.6/lkmpg.pdf
http://www.tldp.org/LDP/lkmpg/2.6/html/index.html

13.

Summary: In this experiment the students improved the modules in the previous
experiment by providing licensing information and also command line arguments.

Module Programming II

Page 91

EXPERIMENT 9 SYSTEM COMMANDS AND REGISTRY INFORMATION


1.

Objectives:
(a). Executing system commands using java code
(b). Reading registry entries
(c). Reading version information through registry

2.

Time Required: 3 hrs

3.

Software Required:
(a). Windows
(b). NetBeans 8/Eclipse Kepler
(c). Borland/Turbo C/Dev++/Visual Studio

4.

System Commands:System Command is a directive to a computer program acting as an interpreter


of some kind, in order to perform a specific task. Most commonly a command is a directive to some
kind of command-line interface, such as a shell.

5.

Type and Execute the following command in DOScmd /c dir. Show the outcome here.

System Commands and Registry Information

Page 92

(1
)

System Commands and Registry Information

Page 93

6.

Now Type following Java code and execute it.


import java.io.*;
public class doscmd
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}

System Commands and Registry Information

Page 94

(1
)

catch(IOException e1) {}
catch(InterruptedException e2) {}
System.out.println("Done");
}
}
What is the outcome? Show here. (Make sure that the working directory is same for both Points 5 and
6).

7.

Write DOS command and Java code to execute CHKDSK. Show outcome of both programs here.

System Commands and Registry Information

Page 95

(2
)

System Commands and Registry Information

Page 96

8.

9.

Windows Registry: Windows Registry is a hierarchical database that stores configuration settings
and options on Microsoft Windows operating systems. It contains settings for low-level operating
system components and for applications running on the platform that have opted to use the Registry.
The kernel, device drivers, services, user interface and third party applications can all make use of the
Registry. The Registry also provides a means to access counters for profiling system performance.
Getting the System Version Program Example: The following example uses the GetVersionEx()
function to display the version of the currently running operating system. Relying on version
information is not the best way to test for a feature. Instead, refer to the documentation for the

System Commands and Registry Information

Page 97

(1

feature of interest. If you must require a particular operating system, be sure to use it as a minimum
supported version, rather than design the test for the one operating system. This way, your detection
code will continue to work on future versions of Windows.

Type the following program and show the outcome.


// #define _WIN32_WINNT 0x0502 // Windows Server 2003 family
// For Win Xp, change accordingly...
#define _WIN32_WINNT 0x0501
// #define _WIN32_WINNT 0x0500 // Windows 2000
// #define _WIN32_WINNT 0x0400 // Windows NT 4.0
// #define _WIN32_WINDOWS 0x0500 // Windows ME
// #define _WIN32_WINDOWS 0x0410 // Windows 98
// #define _WIN32_WINDOWS 0x0400 // Windows 95
#include<windows.h>
#include<stdio.h>
#define BUFSIZE 80

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


{
OSVERSIONINFOEX osver;
BOOL bOsVersionInfoEx;
// Try calling GetVersionEx() using the OSVERSIONINFOEX structure.
System Commands and Registry Information

Page 98

// If that fails, try using the OSVERSIONINFO structure.


ZeroMemory(&osver, sizeof(OSVERSIONINFOEX));
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if(!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) &osver)))
{
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if(!GetVersionEx((OSVERSIONINFO *) &osver))
return FALSE;
else
printf("Buffer for the structure size is OK.\n");
}
else
printf("GetVersionEx() is OK.\n");
switch (osver.dwPlatformId)
{
//Test for the Windows NT product family.
case VER_PLATFORM_WIN32_NT:
// Test for the specific product family.
if(osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2)
printf("Microsoft Windows Server 2003 family, ");
System Commands and Registry Information

Page 99

if(osver.dwMajorVersion == 5 && osver.dwMinorVersion == 1)


printf("Microsoft Windows XP ");
if(osver.dwMajorVersion == 5 && osver.dwMinorVersion == 0)
printf("Microsoft Windows 2000 ");
if(osver.dwMajorVersion <= 4)
printf("Microsoft Windows NT ");
// Test for specific product on Windows NT 4.0 SP6 and later.
if(bOsVersionInfoEx)
{
// Test for the workstation type.
if(osver.wProductType == VER_NT_WORKSTATION)
{
if(osver.dwMajorVersion == 4)
printf("Workstation 4.0 ");
elseif(osver.wSuiteMask & VER_SUITE_PERSONAL)
printf("Home Edition ");
else
printf("Professional ");
}
// Test for the server type.
System Commands and Registry Information

Page 100

elseif(osver.wProductType ==
VER_NT_DOMAIN_CONTROLLER)

VER_NT_SERVER

||

osver.wProductType

{
if((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2))
{
if(osver.wSuiteMask & VER_SUITE_DATACENTER)
printf("Datacenter Edition ");
elseif(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Enterprise Edition ");
elseif(osver.wSuiteMask == VER_SUITE_BLADE)
printf("Web Edition ");
else
printf("Standard Edition ");
}
elseif((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 0))
{
if(osver.wSuiteMask & VER_SUITE_DATACENTER)
printf("Datacenter Server ");
elseif(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Advanced Server ");
System Commands and Registry Information

Page 101

==

else
printf("Server ");
}
// Windows NT 4.0
else
{
if(osver.wSuiteMask & VER_SUITE_ENTERPRISE)
printf("Server 4.0, Enterprise Edition ");
else
printf("Server 4.0 ");
}
}
}
// Test for specific product on Windows NT 4.0 SP5 and earlier
else
{
HKEY hKey;
char szProductType[BUFSIZE];
DWORD dwBufLen=BUFSIZE;
LONG lRet;
System Commands and Registry Information

Page 102

lRet
=
RegOpenKeyEx(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
0,
KEY_QUERY_VALUE,
&hKey);
if(lRet != ERROR_SUCCESS)
return FALSE;
else
printf("RegOpenKeyEx() is OK.\n");
lRet
=
RegQueryValueEx(hKey,
(LPBYTE)szProductType, &dwBufLen);

"ProductType",

if((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))


return FALSE;
else
printf("RegQueryValueEx() is OK.\n");
RegCloseKey(hKey);
if(lstrcmpi("WINNT", szProductType) == 0)
printf("Workstation ");
if(lstrcmpi("LANMANNT", szProductType) == 0)
printf("Server ");
if(lstrcmpi("SERVERNT", szProductType) == 0)
printf("Advanced Server ");
printf("%d.%d ", osver.dwMajorVersion, osver.dwMinorVersion);

System Commands and Registry Information

Page 103

NULL,

NULL,

}
// Display service pack (if any) and build number.
if(osver.dwMajorVersion == 4 && lstrcmpi(osver.szCSDVersion, "Service Pack 6") == 0)
{
HKEY hKey;
LONG lRet;
// Test for SP6 versus SP6a.
lRet
=
"SOFTWARE\\Microsoft\\Windows

RegOpenKeyEx(HKEY_LOCAL_MACHINE,

NT\\CurrentVersion\\Hotfix\\Q246009", 0, KEY_QUERY_VALUE, &hKey);


if(lRet == ERROR_SUCCESS)
{
printf("RegOpenKeyEx() is OK.\n");
printf("Service Pack 6a (Build %d)\n", osver.dwBuildNumber & 0xFFFF);
}
// Windows NT 4.0 prior to SP6a
else
{
printf("%s (Build %d)\n", osver.szCSDVersion, osver.dwBuildNumber & 0xFFFF);
}
System Commands and Registry Information

Page 104

RegCloseKey(hKey);
}
// Windows NT 3.51 and earlier or Windows 2000 and later
else
{
printf("%s (Build %d)\n", osver.szCSDVersion, osver.dwBuildNumber & 0xFFFF);
}
break;
// Test for the Windows 95 product family.
case VER_PLATFORM_WIN32_WINDOWS:
if(osver.dwMajorVersion == 4 && osver.dwMinorVersion == 0)
{
printf("Microsoft Windows 95 ");
if(osver.szCSDVersion[1] == 'C' || osver.szCSDVersion[1] == 'B')
printf("OSR2 ");
}
if(osver.dwMajorVersion == 4 && osver.dwMinorVersion == 10)
{
printf("Microsoft Windows 98 ");
if(osver.szCSDVersion[1] == 'A')
System Commands and Registry Information

Page 105

printf("SE ");
}
if((osver.dwMajorVersion == 4) && (osver.dwMinorVersion == 90))
{
printf("Microsoft Windows Millennium Edition\n");
}
break;
case VER_PLATFORM_WIN32s:
printf("Microsoft Win32s\n");
break;
}
return TRUE;
}

System Commands and Registry Information

Page 106

10
.

Retrieving and Displaying Object, Instance, and Counter Names: The performance data contains
information for a variable number of object types, instances per object, and counters per object type.
Therefore, the number and size of blocks in the performance data varies. To ensure that your
application correctly receives the performance data, you must use the offsets included in the
performance structures to navigate through the data. Every offset is a count of bytes relative to the
structure containing it. The reason the system uses offsets instead of pointers is that pointers are not
valid across process boundaries. The addresses that the process that installs the counters would store
would not be valid for the process that reads the counters. The following example displays the index
and name of each object, along with the indexes and names of its counters. The object and counter
names are stored in the registry, by index. This example creates a function, GetNameStrings(), to
load the indexes and names of each object and counter from the registry into an array, so that they can
be easily accessed. GetNameStrings() uses the following standard registry functions to access the
data: RegOpenKey(), RegCloseKey(), RegQueryInfoKey(), and RegQueryValueEx().
This example creates the following functions for navigating the performance data: FirstObject,
FirstInstance, FirstCounter, NextCounter, NextInstance, and NextCounter. These functions navigate
the performance data by using the offsets stored in the performance structures.
Execute the following programs and show outcome.
// #define _WIN32_WINNT 0x0502 // Windows Server 2003 family
// For Win Xp, change accordingly...
#define _WIN32_WINNT 0x0501

System Commands and Registry Information

Page 107

(1
)

// #define _WIN32_WINNT 0x0500 // Windows 2000


#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define TOTALBYTES

20000

#define BYTEINCREMENT 2048


LPSTR lpNameStrings;
LPSTR *lpNamesArray;
// Functions used to navigate through the performance data.
PPERF_OBJECT_TYPE FirstObject(PPERF_DATA_BLOCK PerfData)
{
return((PPERF_OBJECT_TYPE)((PBYTE)PerfData + PerfData->HeaderLength));
}
PPERF_OBJECT_TYPE NextObject(PPERF_OBJECT_TYPE PerfObj)
{
return((PPERF_OBJECT_TYPE)((PBYTE)PerfObj + PerfObj->TotalByteLength));
}
PPERF_INSTANCE_DEFINITION FirstInstance(PPERF_OBJECT_TYPE PerfObj)
System Commands and Registry Information

Page 108

{
return((PPERF_INSTANCE_DEFINITION)((PBYTE)PerfObj
>DefinitionLength));

PerfObj-

}
PPERF_INSTANCE_DEFINITION
PerfInst)

NextInstance(PPERF_INSTANCE_DEFINITION

{
PPERF_COUNTER_BLOCK PerfCntrBlk;
PerfCntrBlk = (PPERF_COUNTER_BLOCK)((PBYTE)PerfInst + PerfInst->ByteLength);
return((PPERF_INSTANCE_DEFINITION)((PBYTE)PerfCntrBlk + PerfCntrBlk>ByteLength));
}
PPERF_COUNTER_DEFINITION FirstCounter(PPERF_OBJECT_TYPE PerfObj)
{
return((PPERF_COUNTER_DEFINITION) ((PBYTE)PerfObj + PerfObj->HeaderLength));
}
PPERF_COUNTER_DEFINITION
PerfCntr)

NextCounter(PPERF_COUNTER_DEFINITION

{
return((PPERF_COUNTER_DEFINITION)((PBYTE)PerfCntr + PerfCntr->ByteLength));
}
// Load the counter and object names from the registry to the
System Commands and Registry Information

Page 109

// global variable lpNamesArray.


BOOL GetNameStrings()
{
HKEY hKeyPerflib;

// handle to registry key

HKEY hKeyPerflib009;

// handle to registry key

DWORD dwMaxValueLen; // maximum size of key values


DWORD dwBuffer;

// bytes to allocate for buffers

DWORD dwBufferSize;

// size of dwBuffer

LPSTR lpCurrentString;

// pointer for enumerating data strings

DWORD dwCounter;

// current counter index

// Get the number of Counter items.


if(RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib",
0,
KEY_READ,
&hKeyPerflib) != ERROR_SUCCESS)
return FALSE;
else
printf("RegOpenKeyEx() is OK.\n");
System Commands and Registry Information

Page 110

dwBufferSize = sizeof(dwBuffer);
if(RegQueryValueEx(
hKeyPerflib,
"Last Counter",
NULL,
NULL,
(LPBYTE) &dwBuffer,
&dwBufferSize) != ERROR_SUCCESS)
return FALSE;
else
printf("RegQueryValueEx() is OK.\n");
RegCloseKey(hKeyPerflib);
// Allocate memory for the names array.
lpNamesArray = (LPTSTR *)malloc((dwBuffer+1) * sizeof(LPSTR));
if(lpNamesArray == NULL)
return FALSE;
// Open the key containing the counter and object names.
if(RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib\\009",
System Commands and Registry Information

Page 111

0,
KEY_READ,
&hKeyPerflib009) != ERROR_SUCCESS)
return FALSE;
else
printf("RegOpenKeyEx() is OK.\n");
// Get the size of the largest value in the key (Counter or Help).
if(RegQueryInfoKey(
hKeyPerflib009,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
&dwMaxValueLen,
NULL,
NULL) != ERROR_SUCCESS
System Commands and Registry Information

Page 112

)
return FALSE;
else
printf("RegQueryInfoKey() is OK.\n");
// Allocate memory for the counter and object names.
dwBuffer = dwMaxValueLen + 1;
lpNameStrings = (LPTSTR)malloc(dwBuffer * sizeof(CHAR));
if(lpNameStrings == NULL)
{
free(lpNamesArray);
return FALSE;
}
else
printf("Memory allocated for lpNameStrings.\n");
// Read the Counter value.
if(RegQueryValueEx(
hKeyPerflib009,
"Counter",
NULL,
NULL,
System Commands and Registry Information

Page 113

(LPBYTE)lpNameStrings,
&dwBuffer) != ERROR_SUCCESS)
return FALSE;
else
printf("RegQueryValueEx() is OK.\n");
printf("Please wait...\n");
// Load names into an array, by index.
for(lpCurrentString = lpNameStrings; *lpCurrentString;
lpCurrentString += (lstrlen(lpCurrentString)+1))
{
dwCounter = atol(lpCurrentString);
lpCurrentString += (lstrlen(lpCurrentString)+1);
lpNamesArray[dwCounter] = (LPSTR)lpCurrentString;
}
return TRUE;
}
// Display the indexes and/or names for all performance objects, instances, and counters.*
int main()
{
PPERF_DATA_BLOCK PerfData = NULL;
System Commands and Registry Information

Page 114

PPERF_OBJECT_TYPE PerfObj;
PPERF_INSTANCE_DEFINITION PerfInst;
PPERF_COUNTER_DEFINITION PerfCntr, CurCntr;
PPERF_COUNTER_BLOCK PtrToCntr;
DWORD BufferSize = TOTALBYTES;
DWORD i, j;
LONG k;
// Get the name strings through the registry.
if(!GetNameStrings())
return FALSE;
// Allocate the buffer for the performance data.
PerfData = (PPERF_DATA_BLOCK) malloc(BufferSize);
if(PerfData == NULL)
return FALSE;
while(RegQueryValueEx(
HKEY_PERFORMANCE_DATA,
"Global",
NULL,
NULL,
(LPBYTE) PerfData,
System Commands and Registry Information

Page 115

&BufferSize) == ERROR_MORE_DATA)
{
// Get a buffer that is big enough.
BufferSize += BYTEINCREMENT;
PerfData = (PPERF_DATA_BLOCK) realloc(PerfData, BufferSize);
}
// Get the first object type.
PerfObj = FirstObject(PerfData);
// Process all objects.
for(i=0; i < PerfData->NumObjectTypes; i++)
{
// Display the object by index and name.
printf("\nObject %ld: %s\n", PerfObj->ObjectNameTitleIndex, lpNamesArray[PerfObj>ObjectNameTitleIndex]);
// Get the first counter.
PerfCntr = FirstCounter(PerfObj);
if(PerfObj->NumInstances > 0)
{
// Get the first instance.
PerfInst = FirstInstance(PerfObj);
System Commands and Registry Information

Page 116

// Retrieve all instances.


for(k=0; k < PerfObj->NumInstances; k++)
{
// Display the instance by name.
printf("\n\tInstance %S: \n", (char *)((PBYTE)PerfInst + PerfInst->NameOffset));
CurCntr = PerfCntr;
// Retrieve all counters.
for(j=0; j < PerfObj->NumCounters; j++)
{
// Display the counter by index and name.
printf("\t\tCounter %ld: %s\n", CurCntr->CounterNameTitleIndex,
lpNamesArray[CurCntr->CounterNameTitleIndex]);
// Get the next counter.
CurCntr = NextCounter(CurCntr);
}
// Get the next instance.
PerfInst = NextInstance(PerfInst);
}
}
else
System Commands and Registry Information

Page 117

{
// Get the counter block.
PtrToCntr = (PPERF_COUNTER_BLOCK)((PBYTE)PerfObj + PerfObj>DefinitionLength);
// Retrieve all counters.
for(j=0; j < PerfObj->NumCounters; j++)
{
// Display the counter by index and name.
printf("\tCounter %ld: %s\n", PerfCntr->CounterNameTitleIndex,
lpNamesArray[PerfCntr->CounterNameTitleIndex]);
// Get the next counter.
PerfCntr = NextCounter(PerfCntr);
}
}
// Get the next object type.
PerfObj = NextObject(PerfObj);
}
// Release all the memory back to system...
free(lpNamesArray);
free(lpNameStrings);
System Commands and Registry Information

Page 118

free(PerfData);
return TRUE;
}

System Commands and Registry Information

Page 119

11
.

What is your learning in this experiment?

System Commands and Registry Information

Page 120

(4
)

System Commands and Registry Information

Page 121

12
.

References:
http://www.java-samples.com/showtutorial.php?tutorialid=8
https://en.wikipedia.org/wiki/Command_%28computing%29
http://ss64.com/nt/
https://en.wikipedia.org/wiki/List_of_DOS_commands
https://en.wikipedia.org/wiki/Windows_Registry
http://www.tenouk.com/ModuleP.html
http://www.tenouk.com/ModuleP1.html

13
.

Summary: This experiments provides codes to execute system commands as well as to explore
registry entries available in Windows.

System Commands and Registry Information

Page 122

System Commands and Registry Information

Page 123

EXPERIMENT 10 SOCKETS
1.

Objectives:
(a). Sockets
(b). Communication using sockets

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java
(b). Windows
(c). NetBeans 8/Eclipse Kepler

4.

Socket-Definition: A socket is one endpoint of a two-way communication link between


two programs running on the network. A socket is bound to a port number so that the
TCP layer can identify the application that data is destined to be sent.
Server: A server runs on a specific computer and has a socket that is bound to a specific
port number. The server just waits, listening to the socket for a client to make a
connection request.
Client: The client knows the hostname of the machine on which the server (has a socket)
is running and the port number on which the server is listening. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection.

Sockets

Page 124

5.

Socket and ServerSocket: Socket and ServerSocket classes are used to implement
socket programming. ServerSocket has constructors that create new ServerSocket
objects, methods that listen for connections on a specified port, and methods that return a
Socket object when a connection is made so that you can send and receive data. A new
ServerSocket is created on a particular port using a ServerSocket( ) constructor. In
following activity student will be able to find out open port on Local machine.

public ServerSocket(int port) throws IOException, BindException


// (LocalPortScanner.java)
import java.net.*;
import java.io.*;
public class LocalPortScanner{
public static void main(String args[]) throws IOException{
for(int port=1024;port<=65535;port++){
try
{
ServerSocket server=new ServerSocket(port);
}
catch(IOException e)
{
System.out.println("There is a open port"+port);
}
}
Sockets

Page 125

}
}
6.

Implementation of echo client-server Application: This Activity implements a client,


EchoClient that connects to the Echo server. The Echo server simply receives data from
its client and echoes it back. The Echo server is a service built into most operating
systems. EchoClient creates a socket and gets a connection to the Echo server. It reads
input from the user on the standard input stream, and then forwards that text to the Echo
server by writing the text to the socket. The server echoes the input back through the
socket to the client. The client program reads and displays the data passed back to it
from the server.
//(EchoServer.java)
import java.io.*;
import java.net.*;
public class EchoServer{
public EchoServer(int portnum){
try{
server = new ServerSocket(portnum);
}
catch (Exception err){
System.out.println(err);
}
}
public void serve(){
try{

Sockets

Page 126

while (true){
Socket client = server.accept();
BufferedReader
r
=
new
BufferedReader(new
InputStreamReader (client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(),
true);
w.println("Welcome to the Java EchoServer. Type 'bye' to
close.");
String line;
do{
line = r.readLine(); //read from Cleint
if ( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err){
System.err.println(err);
}

Sockets

Page 127

}
public static void main(String[] args){
EchoServer s = new EchoServer(9999);
s.serve();
}
private ServerSocket server;
}

//(EchoClient.java)
import java.io.*;
import java.net.*;
public class EchoClient{
public static void main(String[] args){
try{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader
(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
Sockets

Page 128

BufferedReader
InputStreamReader(System.in));

con

new

BufferedReader(new

String line;
do{
line = r.readLine(); //Read from Server
if ( line != null )
System.out.println(line); //print if not null
line = con.readLine(); //Read from user
w.println(line);

//send to server

}while ( !line.trim().equals("bye") );
}
catch (Exception err){
System.err.println(err);
}
}
}
7.

Execute the code and show the outcome here.

Sockets

Page 129

(2)

8.

Write a code that reads a file from the client and sends to the server. The server then
writes the file at the server end. Show code and output here.

9.

Resources:
http://www.oracle.com/technetwork/java/socket-140484.html

Sockets

Page 130

(8)

http://www.tutorialspoint.com/java/java_networking.htm
14.

Summary: This experiment provides example to create Server Socket and Client
Sockets using Java. The students are then asked to send a file through this connection.

I insist you to strive.


Work, Work and only
work for satisfaction
with patience,
humbleness and serve
thy nation.

Sockets

Page 131

Muhammad Ali Jinnah

A scientist in his laboratory is


not a mere technician: he is
also a child confronting
natural phenomena that
impress him as though they
were fairy tales.
Marie Curie

I have not failed. I've


just found 10,000 ways
that won't work.
Thomas Alva Edison

Sockets

Page 132

Das könnte Ihnen auch gefallen