Você está na página 1de 36

Unix&Network programming

" Study Of Multiuser Operating System and their Features

Course Instructor University

: K.JAVUBAR SATHICK : BSA University

Ihr Logo

Contents to be covered:
Process Environment
Main function
Process Termination. Command-line arguments.

Environment List
Memory layout of C program in unix. Memory Allocation

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Introduction
In this chapter we examine the environment of a single process. We also see how the main function is called when program is executed.

How command-line argument are passed to the new progam.

How the typical memory layout looks like. How to allocate the additional memory. How to use the environment variable. Various ways for process to terminate.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Main function
A c program starts execution with a function called main. The prototype for the main function is int main(int argc, char *argv[]); Where argc is the no. of command-line arguments and argv is an array

of pointers to the arguments.


When C program is executed by kernel -by any one of the exec fn.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Process Termination
There are eight ways for a process to terminate. Normal termination occurs in five ways.

Abnormal termination occurs in three ways.

Five normal termination ways are as follows, 1. Return from main fn.

2. Calling exit fn.


3. Calling _exit or _Exit fn. 4. Return of the last thread from its start routine. 5. Calling pthread_exit from the last thread.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Process Termination
Abnormal termination occurs in three ways.

Three Abnormal termination ways are as follows,

1. Calling abort fn.


2. Receipt of signal. 3. Response of the last thread to cancellation request.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Exit functions
Three functions terminate a program or process normally are as follow _exit() and _exit() which returns to the kernel immediately,

and exit(), which performs certain clean up processing and then returns to the kernel.
#include<stdlib.h> // standard library header file Void exit(int status); // performs clean up work Void _Exit(int status);// no clean up work, returns im to ker #include <unistd.h>// unix standard library header file Void _exit(int status);// no clean up work, returns im to ker

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Command-Line arguments& Environment List


Command-Line Argument:
The term command-line argument can be informally defined as any

parameter that is typed after the name of a program in a command interpreter (such as a DOS box or Unix shell).
For example, if you typed the command rm file.s here "file.s" is a

command-line argument which tells the program rm to remove the file "file.s".
This is the part of normal operation of the unix system shells.

Environment List:
Each program is also passed an environment list, like the argument list. The environment list is an array of character pointers, with each pointer

containing the address of a null-terminated c string.


The address of the array of pointers is contained in the global variable

environ: extern char ** environ


DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Environment List
environment ptr Environ: environment list environment string HOME=/home/sar\0 PATH=/bin:/usr/bin\0 SHELL=/bin/bash\0 USER=sar\0 NULL LOGNAME=sar\0

ENVIRONMENT CONSISTING OF FIVE C CHARACTER STRINGS

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Memory layout of c program


The memory layout of C program as the following segments 1. Text Segment. 2. Intialized data segment. 3. Unintialized data segment. 4.Stack. 5.Heap. 1. Text Segment:
This segment as machine instruction that the cpu executes. Usually, the text segment is sharable so that only a single copy needs to be

in memory for frequently executed programs such as c compiler, the shell so on....
DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Memory layout of c program


2. Intialized data segment: This segment usually called simply the data segment, containing variables that are specifically initialized in the program. For eg int maxcount=35; 3. Uninitialized data segment:

This segment often called as the bss segment block started by symbol.

Data in this segment are initialized by the kernel before the program starts executing.

4. Stack: In this segment, the automatic variables are stored, along with information that is saved each time when the function is called. The space for automatic and temporary variable is stored on the stack.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Typical Memory Arrangement


5. Heap:
In this segment dynamic memory allocation usually takes place.

And the heap is located between uninitialized data segment and stack

segment. high address Stack heap Uninitialized data Initialized data text Low address
Your Logo

command-line agr and env. Var

initialized to zero by exec read from program file by exec

DEPARTMENT OF COMPUTER APPLICATIONS

Memory Allocation
Three functions is used for Memory allocation; 1. Malloc: which allocates the specified no. Of bytes of memory. The initial value of the memory is indeterminate. 2. Calloc: which allocates space for a specified no.of objects of a specified size. The space is initialized to all 0 bits. 3. Realloc: Which increase or decrease the size of previously allocated memory. #include<stdlib.h> Void *malloc(size_t size); Void *calloc(size_t nobj,size_t size); Void *realloc(void* ptr,size_t newsize); Void free(void * ptr);

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Process control
Contents to be covered;
Process Identifier. Fork function. Vfork function. Wait and wait pid function. Race condition. Six exec function.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Process control-process identifier

Every process has unique process id.


candidates for reusability.

Unique pid can be reused, once a process terminates their ids become

This prevents a new process from being mistakenly referred again. Pid with 0 is scheduler process and it is often referred as swapper. In addition to the process id,there are other identifier for every process they are

as follows,
A. pid_t getpid(void) // process id of the calling process. B. pid_t getppid(void) //parent process id of the calling process. C. uid_t getuid(void) //real user id of the calling process. D. uid_t geteuid(void) // effective user id of the calling process so on

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Fork function

An existing process can create a new process by calling the function known as fork which is syntactically referred as Pid_t fork(void);

It creates a new process called child process.

It returns 2values : 1st value throws 0 for child process which indicates

that process can have only single parent process. 2nd value throws pid of the child process for parent process the reason is process can have more than one child.
Reason for 0 in child process is child can have only one parent. Child process can always call getppid to obtain the pid of its parent. The child process is copy of parent.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Vfork function & wait and wait pid function


Same calling sequence as that of fork function. The vfork function is intended to create new process when the purpose of

new process is to exec a new program.


It creates a new process without copying the address space of parent

into child. Wait & wait pid fn:


When a process terminates either normally or abnormally, the kernel

notifies the parent process by sending the SIGCHILD signal to the parent.
Because the child process termination is asynchronous event.so parent

might ignore this signal or it can be handled.


If it decides to handle then parent might call wait and waitpid fn.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

wait and wait pid function


Role of wait and waitpid fn:

It blocks all the child process which are still running. Returns immediately with termination status of the child. Returns immediately with an error.

#include<sys/wait.h> pid_t wait(int *statloc); pid_t waitpid(pid_pid, int *statloc,int options);

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Difference between wait and wait pid function


The wait fn can block the caller until a child process terminates,

whereas waitpid prevents it from blocking.


The waitpid does not wait for the child that terminates first.

features of waitpid fn:

1. the waitpid fn let us wait for one particular process,whereas wait fn will return the status of any terminated child.
2. the waitpid fn provides the non-blocking version of wait. 3. the waitpid fn provides support for job control.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Race condition/ Exec fn


This race condition occurs when multiple processes are trying to do

some work with shared data and final outcome depends on order in which process run.
Fork fn initiates race condition because parent and child process

competes. Six Exec fn:


The exec function is used for execution of the process.
When a process calls one of the exec functions, that process is

completely replaced by the new program starts executing at its main function.
The process Id does not change across an exec, because a new

process is not created; exec merely replaces the current process-its text,data,heap and stack segments with a brand new program from disk.
DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Exec function
#include<unistd.h> Int execl(const char* pathname, const char *arg0,./*(char *)0 */); Int execv(const char *pathname, char *const argv[]); Int execle(const char *pathname,const char *arg0,/* (char *) 0, char*const

envp[]*/);
Int execve(const char *pathname,char *const argv[], char *const envp[]); Int execlp(const char *filename, const char *arg0,./* (char *) 0 */); Int execvp(const char *filename, char *const argv[]); 1. The first difference in these fns is that the 1st four fn take a pathname

argumet,whereas the last 2 take a filename argument. When a filename argument is specified,
2. If filename contains a slash, it is taken as a pathname, otherwise the executable

file is searched for in the dir specified by path environment variable.


DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Relationship of six exec function


Only one of these 6 fns,execve is a system call within the kernel. The other 5 are just library fn that eventually invoke this system call.

execlp

execl

execle

build argv

build argv

build argv execve (system call Within the kernel)

execvp

try each PATH

execv

use environ

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Features Of Unix Operating System

Multitasking

Multitasking refers to OS that executes multiple tasks simultaneously.

UNIX refers to a task as a process. A user can run several commands in background while executing another in the foreground. When a background task is being executing, user can continue doing another task e.g., printing a large document can be performed in the background while editing some other document in the foreground.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Features Of Unix Operating System


Multi-user OS Multi-user refers to an OS that allows multiple users to use the system

simultaneously.
The theory of multi-user system is to approach 100% computer utilization

while reducing the cost per user.

A single user cannot use the printer, disk, memory or CPU 100% of the time. But multiple users can increases the use of these devices and resources by having an OS that manages the resources for them.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Features Of Unix Operating System


Portability

UNIX is highly portability is the ability of the software operating on one machine to operating as efficiently on another, different machine.

Job Control

Job Control on UNIX refers to the ability to control which job is executed in the

foreground, background or is suspended.

Using Job control can increase the productivity of a user by allowing multiple tasks to be juggled back and forth between background, foreground and suspended states.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Features Of Unix Operating System


Hierarchical Structure UNIX uses a hierarchical structure to store and maintain files. This structure

allows maximum flexibility for storing information to resemble its real life structure. Multiple users may be grouped by corporate departments
The UNIX Shell The shell is a very powerful and dynamic UNIX utility. It is the primary interface

to the OS (kernel). It can be interactively programmed or it can be used to write scripts to solve simple to complex problem.
Pipes and Filters Pipes and filters contribute to the power of UNIX. These enable several

commands or utilities to be combined to perform complex functions.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Features Of Unix Operating System


Device Independence UNIX system considers all devices connected to it as files. It hides the machine

architecture from the users, making it easier to write programs that run on different hardware implementations.

System Security user without permission i.e., Invalid users cannot access data, making it easier to write programs that run on different hardware implementations.

Being a multi-user OS, UNIX offers protection to one users information from the

Communication The UNIX system has several built in programs, enabling the user to communicate, transfer files across different UNIX systems and between UNIX and other OS system.
Your Logo

DEPARTMENT OF COMPUTER APPLICATIONS

Features Of Unix Operating System


Programming Capability UNIX is a highly programmable operating system. UNIX facilities the user to develop both system and application programs. Programming in UNIX is of two types they are Shell programming and

Programming in language (Like C, C++, Java, etc).


The programs written in shells are called as Shell files

The command statements in the programs are called as shell Script.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Unix System Overview

Logging in: internal components of os such as kernel,shell etc.

we log in with the name and password where password will be read by the

home/mcaii/myfolder
Files &Directories: File system is a hierarchial arrangements of directories and files.

Directory is a file that contains directory entries.


Some of the attributes of files are 1. type of file,2. size of file,3.owner of the

file,4. permission for file accessing so on


The stat and fstat functions return a structure of information containing all the

attributes of a file.
DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Unix System Overview

File Name: Name in a directory which is used refer the file is called as File name. referred as path name. A path name begin with a slash is often called as absolute pathname or relative path name.

Path Name: A sequence of one or more file names separated by slash can be

Working & Home directory: Every process as working directory.Some times

referred as current working directory(CWD). When we login, the working directory is set to our home directory. It is obtained when we enter a password.
Program & Processes: A program is an executable file residing on the disk in a

directory. An executing instance of program is often referred as process. Every process is referred by the unique ID called process id and it is a non-negative integer.
Process Control: There are 3 primary functions is used for process control they

are fork.exec and waitpid.


DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

File I/O
Most of the file I/O on unix system can be performed using only five functions:

Open Read Write lseek and close

File Descriptor: It is denoted by fd


To the kernel, all open files are referred to by File descriptors. A file descriptor is

a non-negative integer.
When we open an existing file or create a new file,the kernel returns a file

descriptor to the process


When we want to read or write a file. we identify the file with fd that was

returned by open or creat fn as an argument to either read or write


DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

File I/O

Open Function: A file is opened or created by calling the open function

#include<fcntl.h> int open(const char *pathname,int oflag/*mode_t mode*/); returns file descriptor if OK,-1 on error

The pathname is name of the file to open or create. The oflag argument is combination of one or more following operations which is controlled by the <fcntl.h> header.

O_RDONLY O_WRONLY O_RDWR

-open for reading only. -open for writing only. -open for reading and writing. ONE OF THESE 3 CONSTANTS MUST BE SPECIFIED. Your Logo

DEPARTMENT OF COMPUTER APPLICATIONS

File I/O

The following constants are optional O_APPEND,O_CREAT,O_EXCL,O_TRUNC,O_NOCTTY and O_NONBLOCK

Creat Function: A new file can also be created by calling the creat fn.

#include<fcntl.h> int creat(const char *pathname,mode_t mode); returns file descriptor opened for writing only if OK,-1 on error

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

File I/O

Close Function: An open file is closed by calling the close fn.

#include<fcntl.h> int close(int filedes); Returns:0 if OK,-1 on error Lseek Function:


Every open file has an associated current file offset, normally a non

negative integer that measures the number of bytes from beginning of the file.
An open files offset can be set explicitly by calling lseek fn.

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

File I/O
#include<fcntl.h> off_t lseek(int filedes,off_t offset,int whence); Returns: new file offset if OK,-1 on error

The interpretation of the offset depends on the value of the whence argument.
If the whence is SEEK_SET,the files offset is set to offset bytes from

beginning of the file.


If the whence is SEEK_CUR,the files offset is set to its current value plus

the offset.
If the whence is SEEK_END,the files offset is set to the size of the file plus

the offset.
DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

File I/O
Read function: Data is read from open file with read function.

#include<fcntl.h> ssize_t read(int filedes, void *buf, size_t nbytes); Returns:no of bytes read,0 if eof,-1 on error
Write Function: Data is written to an open file with write function

#include<fcntl.h> ssize_t write(int filedes, const void *buf, size_t nbytes); Returns:no of bytes written if OK,-1 on error

DEPARTMENT OF COMPUTER APPLICATIONS

Your Logo

Você também pode gostar