Transcript Document

Network Programming
UBI 510
Chapter 1
Asst.Prof.Muhammed Cinsdikici
1
7/7/2015
1. Introduction

Fundemental to all Operating Systems is the concept of
Process

Processes should interact with each other.

In UNIX based OS’es at any given time t, multiple processes
appear to be executing concurrently.

But only one process is actually being worked on CPU.

The ability of OS to multiplex its resources among multiple
processes is called multiprogramming (or multitasking)

Multiple processing units are called multiprocessing

Program is in execution called part of process.
Asst.Prof.Muhammed Cinsdikici
2
7/7/2015
Program

Program is an inactive, static entity consisting of a set of
instructions and associates data.

Program can be considered as in two basic formats;
– Source program: Series of valid statements for a
specific programming language (such as C/C++). It is
stored in ASCII format.
– Executable program: Source program that by way of
translating program such as a compiler, or an
assembler, has been put into special binary format that
the OS can execute (run). It is not ASCII so in most
cases it can not displayable.
Asst.Prof.Muhammed Cinsdikici
3
7/7/2015
Sample Source Program
/* p1.1.cxx - GNU C++ File Display Hello World 3 times
#include <iostream>
#include <unistd.h>
// needed for write
#include <cstring>
// needed for strcpy
#include <cstdlib>
// needed for exit
using namespace std;
char
*cptr = "Hello World\n"; // static by placement
char
buffer1[25];
int main( ){
void
showit(char *);
// function prototype
int
i = 0;
// automatic variable
strcpy(buffer1, "A demonstration\n"); // library function
write(1, buffer1, strlen(buffer1)+1); // system call
for ( ; i < 3; ++i)
showit(cptr);
// function call
return 0;
}
void showit( char *p ){
char
*buffer2;
buffer2= new char[ strlen(p)+1 ];
strcpy(buffer2, p);
// copy the string
cout << buffer2;
// display string
delete [] buffer2;
// release location
}
Asst.Prof.Muhammed Cinsdikici
*/
4
7/7/2015
2. Library Functions

Function is a collection of declarations and statements that carries out a
specific action and/or returns a value.

They are either defined by user or have been previously defined and
made available to the user.

Previously defined functions are stored in object code format in library
(archive) files

Object code is a special file format that is generated as intermediate step
when an executable program is produced.

Functions stored in library files are often called library functions or
runtime library routines

In most UNIX systems, they are in /usr/lib directory.
Asst.Prof.Muhammed Cinsdikici
5
7/7/2015
Library Functions (cont)

Two basic types of Libraries:
– Static Libraries:
Collections of object files that are used during the linking phase of a
program. Referenced code is extracted from the library and
incorporated in the executable image.
– Shared Object Libraries
Contain relocatable objects that can be shared by more than one
application. During compilation the object code from library is not
incorporated in the executable code only a reference to the object is
made.
When executable using shared object library is loaded into memory,
the appropriate shared object library is loaded and attached to the
image. If the shared object library is already in memory, this copy
is referenced. They are more complex than static libraries.
Asst.Prof.Muhammed Cinsdikici
6
7/7/2015
Library Functions (cont)



By convention, “lib” is used to indicate library files.
The extention of lib files is “a”
UNIX archive utility “ar” is used to
create/modify/extract/examine library file contents.
# ar t /usr/lib/libc.a | pr -4 –t


“libc.a” is for standard C library.
“pr” is utility for displaying output in column
format. “-4” is for 4 columns, “-t” is for removing
header content.
Asst.Prof.Muhammed Cinsdikici
7
7/7/2015
Writing own Library Functions
/* ascii.cxx – GNU C++ file*/
char *
ascii( int start, int finish ){
char *b = new char(finish-start+1);
for (int i=start; i <= finish; ++i)
b[i-start]=(char) i;
return b;
}
Asst.Prof.Muhammed Cinsdikici
8
7/7/2015
Writing own Library Functions
/* change_case.cxx – GNU C++ file*/
#include <ctype.h>
char *
change_case( char *s ){
char *t = &s[0];
while ( *t ){
if ( isalpha(*t) )
*t += islower(*t) ? -32 : 32;
++t;
}
return s;
}
# g++ -c change_case.cxx
# g++ -c ascii.cxx
# ar cr libmy_demo.a ascii.o change_case.o
Asst.Prof.Muhammed Cinsdikici
9
7/7/2015
Using your own Library Functions
/* my_demo.h – GNU Header file*/
/*
Prototypes for my_demo library functions
*/
#ifndef MY_DEMO_H
#define MY_DEMO_H
char * ascii( int, int );
char * change_case( char * );
#endif
Asst.Prof.Muhammed Cinsdikici
10
7/7/2015
Using your own Library Functions
/* main.cxx – GNU C++ file*/
#include <iostream>
#include "my_demo.h"
using namespace std;
int
main( ) {
int start, stop;
char b[20];
// temp string buffer
cout << "Enter start and stop value for string: ";
cin >> start >> stop;
cout << "Created string : " << ascii(start, stop) << endl;
cin.ignore(80,'\n');
cout << "Enter a string : ";
cin.getline(b,20);
cout << "Converted string: " << change_case( b ) << endl;
return 0;
}
Asst.Prof.Muhammed Cinsdikici
11
7/7/2015
Using your own Library Functions
# g++ -o main main.cxx –L. –lmy_demo
-L is for indicating current directory.
-l is for importing our library. Notice that not “libmy_demo”
Execution result is something like;
Asst.Prof.Muhammed Cinsdikici
12
7/7/2015
3. System Calls
Asst.Prof.Muhammed Cinsdikici
13
7/7/2015
3. System Calls (cont)

System calls are requests done by either functions or
programs that ask the OS directly perform some work.
When a system call is issued, an executing program
switches from user mode to kernel mode.
– User mode: with user privilidges and access permissions
– Kernel mode: with root/system privilidges and access permissions.

The switching from user mode to kernel mode causes a
certain amount of overhead and in some cases makes a
system call less efficient than a library function.
Asst.Prof.Muhammed Cinsdikici
14
7/7/2015
4. Linking Object Code

Code library files, predifined or user-defined, is combined
with object code from the source program at compile time on
an as-needed basis.

In C/C++ additional library functions can be specified at
compile time by “-l” compiler option.
#gcc prgm.c –lm

-lm; means additional math library functions are linked. Math
library functions are not at standart library location.(i.e.
Libc.a)
Asst.Prof.Muhammed Cinsdikici
15
7/7/2015
5. Managing Failures

If a system call or a library function is unsuccessful, it
returns a value –1 and assigns a value to an external
variable called errno to indicate what the actual error is.

<sys/errno.h> header file contains the defined constants
for all error codes.

The library function perror can be used to produce an
error message.
Include
Files
<stdio.h>
Summary
Void perror (const char *s)
Return
Success
Asst.Prof.Muhammed Cinsdikici
Manual
Section
Failure
3
Sets errno
16
7/7/2015
Sample Code of Failures (cont)
/* p1.2.cxx – GNU C++ file- Checking errno and using perror */
#include <iostream>
#include <cstdio>
// needed for perror
#include <cstdlib>
// needed for exit
#include <unistd.h>
// needed for read and write
using namespace std; extern int errno;
Int main(int argc, char *argv[ ]) {
int n_char = 0,
// # of chars read
buffer[10];
// temporary buffer
// Initially n_char is set to 0 and errno is 0 by default
cout << "n_char = " << n_char << "\t errno = " << errno << endl;
// Display a prompt to stdout
n_char = write(1, "Enter a word: ", 15);
// Use the read system call to obtain 10 characters from stdin
n_char = read(0, buffer, 10);
cout << "n_char = " << n_char << "\t errno = " << errno << endl;
if (n_char == -1) {
// If the read has failed
perror(argv[0]);
exit(1);
}
n_char = write(1, buffer, n_char); // Display the characters read
Asst.Prof.Muhammed
Cinsdikici
return
0;
17
7/7/2015
Sample Code of Failures (cont)

P1.2.cxx program execution result for normal run

P1.2.cxx program execution result for erronous run

Change read(3,buffer,10) See the errno and related msg.
Asst.Prof.Muhammed Cinsdikici
18
7/7/2015
6. Executable File Format

In a Linux environment, source files that have been compiled
into an executable form to be run by the system are put into a
special format called ELF

Files in ELF format contain;
–
–
–
–
–
–

Header entry (specifying HW/Program characteristics)
Program text
Data
Relocation info
Symbol table
String table
Old UNIX executable files in a.out format (Assembler OUtpuT
Format) It is still used as default output from C/C++ compiled
executables.
Asst.Prof.Muhammed Cinsdikici
19
7/7/2015
7. System Memory

In Unix, when an executable program is read into system
memory by kernel it becomes a process. The system memory is
divided into two regions:
– User space: the space where the user processes will run (in
user mode) All users spaces are prevented to interfere each
other.
– Kernel space: the space where the kernel executes and
provides its services

User spaces can only access kernel space through the system
calls. In this case the process is said to be in the kernel mode
and the change in mode is called a context switch.
Asst.Prof.Muhammed Cinsdikici
20
7/7/2015
8. Process Memory

When residing in memory, a user process is divided into three
segments:
– Text segment: contains the executable program code and
constant data. This segment is marked by OS as read-only.If
the processes share the same text segment, then system
references the previously loaded text segment rahter than
then reloading a duplicate. (In program 1.1 “main” and
“showit” would be found in text segment.)
– Data segment: contains the initialized data and uninitialized
data segments (In program 1.1, cptr would be found in
initialized area and the buffer1 in the uninitialized area. The
call to the library routine “new” in the showit function is a
request for additional data segment space. So new, malloc,
calloc in turn make use of system calls brk/sbrk to extend
size of data segment. This extended area is sometimes called
as heap )
– Stack segment: used by the process for storage of variables.
(The identifier “i”, buffer2 and for loop are stored in stack
segment)
Asst.Prof.Muhammed Cinsdikici
21
7/7/2015
8. Process Memory (cont)
The address information is available to the process via referencing
the external variables etext, edata, end.
Asst.Prof.Muhammed Cinsdikici
22
7/7/2015
9. “u” Area

In addition to the text, data and stack segments, the OS also
maintains a region called u-area (user area).

This u area contains information specific to the process such as
open files, current directory, signal actions etc and a system
stack segment for process use.

If the process makes a system call(i.e. İn Program 1.1. system
call to “write”), the stack frame information for the system call
would be stored in the system stack segment.

Processes(itself) normally do not have access to this area and

They have to use system calls to receive information from this
area.
Asst.Prof.Muhammed Cinsdikici
23
7/7/2015
10. Process Memory Addresses
/* p1.3.cxx – GNU C++ File */
/*
Displaying process segment addresses
*/
#include <iostream>
extern int etext, edata, end;
using namespace std;
// Special Thanks to my student Durmus Celeb for the correction belov
typedef int cinsint; //If 32bit compiler is used
typedef long int cinsint; //If 64 bit compiler is used
int
main( ){
cout << "Adr etext: " << hex << cinsint(&etext) << "\t ";
cout << "Adr edata: " << hex << cinsint(&edata) << "\t ";
cout << "Adr end: " << hex << cinsint(&end ) << "\n";
return 0; The address information is available to the process
}
via referencing the external variables etext, edata,
end.
Asst.Prof.Muhammed Cinsdikici
24
7/7/2015
Process Memory Addresses(cont)
/* p1.4.cxx – GNU C++- Program 1.1 modified to display identifier addresses*/
#include <iostream>
#include <unistd.h>
// needed for write
#include <cstring>
// needed for strcpy
#include <cstdlib>
// needed for exit
// Special Thanks to my student Durmus Celeb for the correction belov
typedef int cinsint; //If 32bit compiler is used
typedef long int cinsint; //If 64 bit compiler is used
using namespace std;
char
*cptr = "Hello World\n";// static by placement
char
buffer1[25];
inline void SHW_ADR(char *ID, cinsint address){
cout << "The id " << ID << "\t is at : " << hex << address << endl;
}
extern int etext, edata, end;
int main( ){
void
showit(char *); // function prototype
int
i = 0;
// automatic variable
// display addresses
cout << "Adr etext: " << hex << cinsint(&etext) << "\t ";
Asst.Prof.Muhammed Cinsdikici
cout << "Adr edata: " << hex << cinsint(&edata) << "\t ";
25
7/7/2015
Process
Memory
Addresses(cont)
SHW_ADR("main", cinsint(main));
// function addresses
SHW_ADR("showit", cinsint(showit));
SHW_ADR("cptr", cinsint(&cptr));
// static
SHW_ADR("buffer1", cinsint(&buffer1));
SHW_ADR("i", cinsint(&i));
// automatic
strcpy(buffer1, "A demonstration\n");// library function
write(1, buffer1, strlen(buffer1)+1);// system call
showit(cptr);
// function call
return 0;
}
void showit( char *p ){
char
*buffer2;
SHW_ADR("buffer2", cinsint(&buffer2)); // display address
if ((buffer2= new char[ strlen(p)+1 ]) != NULL){
strcpy(buffer2, p);
// copy the string
cout << buffer2;
// display string
delete [] buffer2;
// release location
} else {
cerr << "Allocation error.\n";
exit(1); } }
Asst.Prof.Muhammed Cinsdikici
26
7/7/2015
Process
Memory
Addresses(cont)
The Output of the p1.4.cxx program...
Asst.Prof.Muhammed Cinsdikici
27
7/7/2015
11. Creating a Process
•Processes are created by fork system call. If the call fails, it returns
“–1” and set errno to one of the error conditions. The failure might
be due to system limit for number of processes exceeded there is no
enough swap space (errno = 11 EAGAIN Resource temporarily
unavailable, errno=12 ENOMEM cannot allocate memory)
•If successful, the fork returns the process ID of the child process in
the parent process and it returns a 0 in the child process. This allows
a process to check if it is a parent or child process.
Include Files
Summary
Return
<sys/types.h>
<unistd.h>
Pid_t fork (void)
Success
Failure
0 in child
-1
Child ID in
parent
Asst.Prof.Muhammed Cinsdikici
Manual
Section
2
Sets errno
Yes
28
7/7/2015
11. Creating a Process (cont)
/*p1.5.cxx – GNU C++ File*/
/* First example of a fork system call (no error check) */
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int
main( ) {
cout << "Hello\n";
fork( );
cout << "bye\n";
return 0;
}
Asst.Prof.Muhammed Cinsdikici
29
7/7/2015