Title: Network Programming
1Network Programming
21. Introduction
- All processes have a processing environment (not
to be confused with environment variables that
are, as we will see, just one part of the
processing environment) - The processing environement consists of a unique
set of information and conditions that is
determined by the current state of the system and
by the parent of the process. - A process can access processing environment
information and in some cases, modif it. - This is accomplished either directly or by using
the appropriate system calls or library functions.
32. Process ID
- Associated with each process is a unique positive
integer identification number called process ID
(PID). - In Solaris, process 0 is sched, process 1 is
init and process 2 is pageout - In Linux, process 0 is swapper, process 1 is
init and process 2 is eventd - swapper is created from startup scratch.
initializes kernel - data structures and creates init.
- init creates a number of special kernel
threads to handle - system management. These special threads have
low PIDs - The system call getpid can be used to obtain the
process id. Ex - printf(My PID is d \n, getpid( ))
- Every process has an associated parent process ID
(PPID) which can be obtained by getppid system
call.
4getpid
- All other PIDs assigned from free PIDs as
increasing until reaching to the PID_MAX value. - Getpid is used to obtain PID.
- Usually the PID will be different on each
invocation of the program.
Include Files ltsys/types.hgt ltunistd.hgt ltsys/types.hgt ltunistd.hgt Manual Section 2
Summary Pid_t getpid (void) Pid_t getpid (void) Pid_t getpid (void) Pid_t getpid (void)
Return Success Failure Sets errno Sets errno
Return The PID -1 Yes Yes
53. Parent Process ID
- Every process has an associated parent process ID
(PPID) which can be obtained by getppid system
call. - Unfortunately there is no system call that allows
a parent process to determine the PIDs of all
its child processes (only available next PID is
given by system) Parent, only knows the PIDs of
its childrens from the fork system call.
Include Files ltsys/types.hgt ltunistd.hgt ltsys/types.hgt ltunistd.hgt Manual Section 2
Summary Pid_t getppid (void) Pid_t getppid (void) Pid_t getppid (void) Pid_t getppid (void)
Return Success Failure Sets errno Sets errno
Return The parent PID -1 Yes Yes
64. Process Group ID
- Every process belongs to a process group that is
identified by an integer process group id value. - When the OS generates a child, it automatically
generates a group. The initial parent process is
known as the process leader. - If a process leader is killed, then all other
processes in that group are killed. The system
call getpgid provides the group id. (if getpgid
returns 0 this means, process itself)
Include Files ltsys/types.hgt ltunistd.hgt ltsys/types.hgt ltunistd.hgt Manual Section 2
Summary Pid_t getpgid (pid_t pid) Pid_t getpgid (pid_t pid) Pid_t getpgid (pid_t pid) Pid_t getpgid (pid_t pid)
Return Success Failure Sets errno Sets errno
Return The process GID -1 Yes (1-EPERM not owner, 3-ESRCHno such process) Yes (1-EPERM not owner, 3-ESRCHno such process)
7Sample PGID Code
- /p2.1.cxx GNU C File/
- / Displaying process group ID information. /
- define _GNU_SOURCE
- include ltiostreamgt
- include ltsys/types.hgt
- include ltunistd.hgt
- using namespace std
- int main( )
- cout ltlt "\n\nInitial process \t PID " ltlt
getpid() ltlt "\t PPID "ltlt getppid() - ltlt "\t GID " ltlt getpgid(0) ltlt endl ltlt
getpgid(pid_t(getppid())) ltlt endl - for (int i 0 i lt 3 i)
- if (fork( ) 0) //
Generate some processes - cout ltlt "New process \t PID " ltlt
getpid() - ltlt "\t PPID "ltlt getppid()
- ltlt "\t GID " ltlt getpgid(0)
- ltlt endl
- return 0
-
8Sample PGID Code
Output of p2.1.cxx file...
9Setting Process Group ID
- If the parent of a process dies, the process init
inherits the child process and becomes its foster
parent. In this case, process group id does not
change. - A process may change its process group by using
the system call setpgid. - Process Group ID ? Processs Group ID
Include Files ltsys/types.hgt ltunistd.hgt ltsys/types.hgt ltunistd.hgt Manual Section 2
Summary int setpgid (pid_t pid, pid_t pgid) int setpgid (pid_t pid, pid_t pgid) int setpgid (pid_t pid, pid_t pgid) int setpgid (pid_t pid, pid_t pgid)
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes (1-EPERM not owner, 3-ESRCHno such process, 22-EIVAL Invalid argument) Yes (1-EPERM not owner, 3-ESRCHno such process, 22-EIVAL Invalid argument)
105. Permissions
- All Unix files have owner, group and other users.
- These users are granted read, write and execute
rights. -
- Same criterion applies to the directories with a
difference that execute corresponds to
examination of the directory. At system level,
the permissions of a file are modified by using
the chmod command.
115. Permissions (cont)
- When the UNIX creates files, the permissions are
assigned by default which is determined by
XORing the creation mask and the umask. - The creation mask has default value
- 777 for executables
- 666 for text files.
- The default umask is 022. The umask value can be
changed by umask command.
12Default Permissions Example
136. Real Effective User GID
- Unix keeps two different user ids for processes
and groups - real user id, real group id
- effective user id, effective group id
- In the example above, first 500 is the real
user ID and second 500 is real group ID. (lt500
IDs generaly used for user logins with special
status) - You can search the group IDs and corresponding
group names from /etc/groups file.
146. Real Effective User GID (cont)
- The OS will use the real ids for things such as
process accounting or sending mail - The OS will use the effective ids for to
determine what additional permissions should be
granted to the process. - Most of the time, real and effective ids are
identical. - Sometimes, the owner of a file may grant his own
privileges to the executing user. This is done by
setting the u-id bit in i-node. (SUID and SGID).
This will tell the OS that when the program is
run by some other user, the resulting process
should have the privileges of the owner. That is
the effective user id of the process becomes the
owner of the file. The system level command id
displays the current user and group ids.
156. Real Effective User GID(cont)
- r-s in the example belov indicates that when
this program is run, the process should have the
privilidges of the file owner (which is root) - The set-user information is stored by the systems
in a 10.th permission bit and can be modified
using the system level command chmod.
Include Files ltsys/types.hgt ltunistd.hgt ltsys/types.hgt ltunistd.hgt Manual Section 2
Summary Uid_t getuid (void) Uid_t geteuid (void) gid_t getgid (void) gid_t getegid (void) Uid_t getuid (void) Uid_t geteuid (void) gid_t getgid (void) gid_t getegid (void) Uid_t getuid (void) Uid_t geteuid (void) gid_t getgid (void) gid_t getegid (void) Uid_t getuid (void) Uid_t geteuid (void) gid_t getgid (void) gid_t getegid (void)
Return Success Failure Sets errno Sets errno
Return Requested ID
167. File System Information
- When A child process is generated, it receives a
copy of its parents file descriptor table (this
includes stdin, stdout and stderr.) with file
pointer offset associsated with each open file.
If file is marked as shared, then OS will need to
save each file pointers offsets seperately.
177. File System Information
- In addition to the process ID information, the
process environment contains file system
information. - For each open file, the OS uses an 1024-entry
index (integer) as an index to file descriptor
table that is located in the u (user) area of the
process. - The file descriptor table references a system
file table which is located in kernel space. - The system file table maps to a system inode
table that contains reference to a more complete
internal description of the file.
188. File Information
- There are a number of system calls used to obtain
file info. Stat is one of them.
Include Files ltsys/types.hgt ltsys/stat.hgt ltunistd.hgt ltsys/types.hgt ltsys/stat.hgt ltunistd.hgt Manual Section 2
Summary int stat(const char file_name, struct stat buf) int fstat(int fildes, struct stat buf) int lstat(const char file_name, struct stat buf) int stat(const char file_name, struct stat buf) int fstat(int fildes, struct stat buf) int lstat(const char file_name, struct stat buf) int stat(const char file_name, struct stat buf) int fstat(int fildes, struct stat buf) int lstat(const char file_name, struct stat buf) int stat(const char file_name, struct stat buf) int fstat(int fildes, struct stat buf) int lstat(const char file_name, struct stat buf)
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes Yes
198. File Information(cont)
- lstat system call is similar to stat except
when the file referenced is a symbolic link. In
the case of a symbolic link, lstat returns info
aout the link entry, while stat returns info
about actual file. - fstat takes the integer file descriptor value
of an open file as its first argument. - Lookup detailed stat structure from
/usr/include/bits/stat.h
20Sample Code for Stat
- / p2.2.cxx GNU C File- Using the stat
system call / - include ltiostreamgt
- include ltcstdiogt
- include ltsys/types.hgt
- include ltsys/stat.hgt
- include ltunistd.hgt
- using namespace std
- const int N_BITS 3
- Int main(int argc, char argv )
- unsigned int mask 0700
- struct stat buff
- static char perm "---", "--x", "-w-",
"-wx", - "r--", "r-x", "rw-",
"rwx" - if (argc gt 1)
- if ((stat(argv1, buff) ! -1))
- cout ltlt "Permissions for " ltlt argv1 ltlt "
" - for (int i3 i --i)
- cout ltlt perm(buff.st_mode mask) gtgt
(i-1)N_BITS - mask gtgt N_BITS
Output of the code
21Modify File Access Permissions
- In a programming environment, access permissions
of the file can be modified by chmod/fchmod
system calls. - chmod takes a character pointer reference to a
file path as its first argument - fchmod takes integer file descriptor value of
open file.
Include Files ltsys/types.hgt ltsys/stat.hgt ltsys/types.hgt ltsys/stat.hgt Manual Section 2
Summary int chmod(const char path, mode_t mode) int fchmod(int fildes, mode_t mode) int chmod(const char path, mode_t mode) int fchmod(int fildes, mode_t mode) int chmod(const char path, mode_t mode) int fchmod(int fildes, mode_t mode) int chmod(const char path, mode_t mode) int fchmod(int fildes, mode_t mode)
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes Yes
22Umask Role on File Access Permissions
- When invoked, umask both changes umask value to
the octal integer value passed and returns old
umask value. - If you use umask system call to determine the
current umask setting, you should call umask
second time, passing it vaue returned from the
first call, to restore the settings to their
initial state - Mode_t cur_mask
- Cur_mask umask(0)
- Cout ltlt Current mask ltlt setfill (0) ltlt
setw(4) ltlt oct ltlt cur_mask ltlt endl - Umask(cur_mask)
Include Files ltsys/types.hgt ltsys/stat.hgt ltsys/types.hgt ltsys/stat.hgt Manual Section 2
Summary Mode_t umask(mode_t mask) Mode_t umask(mode_t mask) Mode_t umask(mode_t mask) Mode_t umask(mode_t mask)
Return Success Failure Sets errno Sets errno
Return The previous umask
23File Path Functions
- Getcwd is used to copy the absolute path of the
current working directory of a process to an
allocated location. - If the argument is set to NULL, getcwd uses
malloc to automaticaly allocate storage space.
Include Files ltunistd.hgt ltunistd.hgt Manual Section 3
Summary Char getcwd(char buf, size_t size) Char getcwd(char buf, size_t size) Char getcwd(char buf, size_t size) Char getcwd(char buf, size_t size)
Return Success Failure Sets errno Sets errno
Return A pointer to the current dir name NULL Yes Yes
- chdir is used to change the current working
directory. - fchdir takes open file descriptor of directory.
Include Files ltunistd.hgt ltunistd.hgt Manual Section 3
Summary int chdir (const char path) int fchdir (int fildes) int chdir (const char path) int fchdir (int fildes) int chdir (const char path) int fchdir (int fildes) int chdir (const char path) int fchdir (int fildes)
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes Yes
249. Process Resource Limits
- Since the system resources are finite, every
process is subject to certain limits. At the
command line, the ulimit command (found in Bourne
shell) displays and modifies the current limits
available to shell and the processes that are
started it. - Ulimit Ha displays the hard limits of the
system. The Hard limits can be increased only by
the superuser. - Ulimit Sa displays the soft limits of the
system. The Soft limits can be set by user.
Notice that stack size is limited in Sa parameter
space
259. Process Resource Limits (cont)
- Historically, the ulimit system call was used
to obtain the part of the resource limit
information. In more recent versions of OSs,
ulimit is superseded by the getrlimit/setrlimit
calls. - Setrlimit can only be used by superuser.
Include Files ltulimit.hgt ltulimit.hgt Manual Section 3
Summary long ulimit(int cmd / , long newlimit / ) long ulimit(int cmd / , long newlimit / ) long ulimit(int cmd / , long newlimit / ) long ulimit(int cmd / , long newlimit / )
Return Success Failure Sets errno Sets errno
Return Nonnegative long integer -1 Yes Yes
Include Files ltsys/time.hgt ltsys/resource.hgt ltunistd.hgt ltsys/time.hgt ltsys/resource.hgt ltunistd.hgt Manual Section 2
Summary int getrlimit (int resource, struct rlimit rlim ) int setrlimit (int resource, const struct rlimit rlim ) int getrlimit (int resource, struct rlimit rlim ) int setrlimit (int resource, const struct rlimit rlim ) int getrlimit (int resource, struct rlimit rlim ) int setrlimit (int resource, const struct rlimit rlim ) int getrlimit (int resource, struct rlimit rlim ) int setrlimit (int resource, const struct rlimit rlim )
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes Yes
26Sample Code for Resource Limit
- / p2.3.cxx GNU C File- Using getrlimt to
display system resource limits / - include ltiostreamgt
- include ltiomanipgt
- include ltsys/time.hgt
- include ltsys/resource.hgt
- using namespace std
- Int main( )
- struct rlimit plimit
- char label "CPU time", "File size",
- "Data segment", "Stack
segment", - "Core size","Resident set
size", - "Number of processes", "Open
files", - "Locked-in-memory", "Virtual
memory", - 0
- int constant RLIMIT_CPU , RLIMIT_FSIZE,
- RLIMIT_DATA , RLIMIT_STACK,
- RLIMIT_CORE , RLIMIT_RSS,
- RLIMIT_NPROC ,
RLIMIT_NOFILE, - RLIMIT_MEMLOCK, RLIMIT_AS
2710. Signaling Process
- Processes receive signals when an out of ordinary
event occurs. - Signals are asynchronous and are generated when
an event occurs that requires attention. - Sources of signals may be
- Hardware (divide by zero)
- Kernel (notifying that an i/o is complete)
- Other processes (a child notifies the parent that
it has terminated) - User Interrupt from keyboard
- Signals are numbered and historically were
defined in the header file ltsignal.hgt in Linux
box, signals are defined in - ltbits/signum.hgt. This file is automaticaly
included when you include ltsignal.hgt in the code.
So, signum.h couldnt - be directly included in the code......
2810. Signaling Process (cont)
- Upon receiving the signal, a process can take
three courses of action - Perform the system specified default for the
signal (for most signals this leads to
termination of the process) - Notify parent about terminating
- Generate core file
- Terminate
- Ignore the signal (this may not be possible all
the time. For ex. SIGSTOP (23) and SIGKILL(9) can
not be ignored) By these special signals, OS
remove errant processes. - Catch the signal (excluding SIGSTOP and SIGKILL)
The process invokes a special signal handling
routine and after its completion the process
continues its execution from where it had left. - A child inherits the signal actions from its
parent. However, if another executable is
overlayed, such as by issuing an exec call, the
all the signal catching routines are reset to
their default.
2911. Command Line Values
- Part of the processing environment of every
process are the values passed to the process in
the main function. - These values can be from the command line or may
be passed to a child process from the parent via
an exec system call. - These values are stored in an array called argv.
- The number of elements in argv array is stored in
an integer argc. - In programs the getopt library function can be
used to learn the contents of argv.
30Sample Code for Command Line Values
/ Displaying the contents of argv (the
command line) / include ltiostreamgt using
namespace std int main(int argc, char argv
) for ( argv argv ) cout ltlt argv
ltlt endl return 0
31Sample2 Code for Command Line Values
/ p2.6.cxx GNU C File- Command line using
getopt / define _GNU_SOURCE include
ltiostreamgt include ltcstdlibgt include
ltunistd.hgt using namespace std extern char
optarg extern int optind, opterr,
optopt Int main(int argc, char argv ) int
c char optstring "abs" opterr
0 // turn off auto err
mesg while ((c getopt(argc, argv, optstring))
! -1) switch (c) case 'a' cout
ltlt "Found option a\n" break case
'b' cout ltlt "Found option b\n"
break case 's' cout ltlt "Found option
s with an argument of " cout ltlt atoi(optarg)
ltlt endl break case '?' cout ltlt
"Found an option that was not in optstring.\n"
cout ltlt "The offending character was " ltlt
char(optopt) ltlt endl if (optind lt
argc) cout ltlt (argc - optind) ltlt " arguments
not processed.\n" cout ltlt "Left off at " ltlt
argvoptind ltlt endl return 0
3212. Environment Variables
- Each process also has access to a list of
environment variables. The environment variables,
like the command-line values, are stored as
ragged array of characters. - Environment variables, which are most commonly
set at the shell level (env) are passed to a
process by its parent when the process begins
execution. - Environment variables can be accessed in a
program by using an external pointer called
environ, which is defined as - Extern char environ
- In most older Linux versions
- Main (int argc, char argv, char envp / OR
as envp/)
33Sample Code for Environment Variables
- / p2.7.cxx GNU G File /
- / Using the environ pointer to display the
command line / - include ltiostreamgt
- using namespace std
- extern char environ
- int
- main( )
- for ( environ )
- cout ltlt environ ltlt endl
- return 0
-
34Get/Put Environment Variables
- The two library calls shown in belov can be used
to manuplate environment variables
Include Files ltunistd.hgt ltunistd.hgt Manual Section 3
Summary Char getenv(const char name) Char getenv(const char name) Char getenv(const char name) Char getenv(const char name)
Return Success Failure Sets errno Sets errno
Return Pointer to the value in the environment NULL
Include Files ltstdlib.hgt ltstdlib.hgt Manual Section 3
Summary int putenv(const char name) int putenv(const char name) int putenv(const char name) int putenv(const char name)
Return Success Failure Sets errno Sets errno
Return 0 -1 Yes Yes
35Sample Code for Getenv
- / p2.8.cxx GNU G File /
- / Displaying the contents of the TERM
variable / - include ltiostreamgt
- include ltcstdlibgt
- using namespace std
- int
- main( )
- char c_ptr
- c_ptr getenv("TERM")
- cout ltlt "The variable TERM is "
- ltlt (c_ptrNULL ? "NOT found" c_ptr)
- ltlt endl
- return 0
-
36Sample Code for Putenv
- / p2.9.cxx GNU G File /
- / Using putenv to modify the environment as
seen by parent - child / - define _GNU_SOURCE
- include ltiostreamgt
- include ltcstdlibgt
- include ltsys/types.hgt
- include ltunistd.hgt
- using namespace std
- extern char environ
- int show_env( char )
- int
- main( )
- int numb
- cout ltlt "Parent before any additions
" ltlt endl - show_env( environ )
- putenv("PARENT_EDparent")
- cout ltlt "Parent after one addition
" ltlt endl - show_env( environ )
- if ( fork( ) 0 ) // In the
CHILD now
// In the PARENT now sleep( 10 )
// Make sure child is done cout ltlt
"Parent after child is done " ltlt
endl numb show_env( environ ) cout ltlt
"... and at address " ltlt hex ltlt environnumb
ltlt " is ... " ltlt ((environnumb)
NULL ? "Nothing!" (environnumb)) ltlt
endl return 0 / Display the contents of
the passed list ... return number found / int
show_env( char cp ) int i for (i0 cp
cp, i) cout ltlt "" ltlt hex ltlt cp ltlt " "
ltlt cp ltlt endl return i
37EXERCISE
/ Sam's environment program / define
_GNU_SOURCE include ltiostreamgt include
ltcstdlibgt include ltsys/types.hgt include
ltunistd.hgt using namespace std int main( )
int numb char p putenv("DEMOabcdefghijklmn
op") p getenv("DEMO") cout ltlt "1. Parent
environment has " ltlt p ltlt endl if ( fork( )
0 ) // In the CHILD now
(p 9) 'X' // Change ref
location p getenv("DEMO") cout ltlt "2.
Child environment has " ltlt p ltlt endl cout
ltlt "3. Exiting child." ltlt endl return 0
// In the
PARENT now sleep( 10 )
// Make sure child is done cout ltlt "4. Back in
parent." ltlt endl p getenv("DEMO") cout ltlt
"5. Parent environment has " ltlt p ltlt endl
return 0
Sam figures he has a way for a child process to
communicate with its parent via environment. His
solution is to have the child process modify
(without changing the storage size and without
using putenv) an environment variable that was
initially found in the parent. He wrote the
following program to test his idea. Will his
program work as he thought why ? Or why not ?
3813. /proc Filesystem
- Linux implements a special virtual filesystem
called /proc that stores information about the
kernel, kernel data structures and the state of
each process and associated threads - /proc is stored in memort not on disk
- The majority of information provided is read-only
- Vary from Linux to another Linux
- Standart system calls (i.e. Open, read etc.) can
be used by programs to access /proc - Linux provides procinfo command that generates a
formatted display of /proc information.
39Sample Code for /proc
- / p2.10.cxx GNU G File -
- Determining Process ID by reading the
contents of - the symbolic link /proc/self
- /
- define _GNU_SOURCE
- include ltiostreamgt
- include ltcstdlibgt
- include ltsys/types.hgt
- include ltunistd.hgt
- using namespace std
- const int size 20
- int
- main( )
- pid_t proc_PID, get_PID
- char buffersize
- get_PID getpid( )
- readlink("/proc/self", buffer, size)
- proc_PID atoi(buffer)
- cout ltlt "getpid " ltlt get_PID ltlt endl
40Readlink Function
Readlink system call reads the symbolic link
referenced by path and stores this data in the
location referenced by buf. A wide array of data
on each process is kept by the operating system.
This data is found in the /proc directory in a
decimal number subdirectory named for the
processs ID. Each process subdirectory
includes Cmdline A file that contains the
cmd-line argument list that started the process.
Cpu When present this file contains CPU
Utilization information Cwd Current working
directory pointer (symbolic link)
Include Files ltsys/types.hgt ltsys/types.hgt Manual Section 2
Summary int readlink (const char path, char buf, size_t bufsiz) int readlink (const char path, char buf, size_t bufsiz) int readlink (const char path, char buf, size_t bufsiz) int readlink (const char path, char buf, size_t bufsiz)
Return Success Failure Sets errno Sets errno
Return Number of characters read -1 Yes Yes
41Readlink Function
include ltiostreamgt include ltfstreamgt include
ltsstreamgt include ltsys/types.hgt include
ltunistd.hgt using namespace std const int size
512 int main( ) ostringstream oss
(ostringstreamout) oss ltlt "/proc/" ltlt
getpid( ) ltlt "/cmdline" cout ltlt "Reading from
file " ltlt oss.str() ltlt endl static char
buffersize ifstream i_file
i_file.open(oss.str().c_str()) // open to
read i_file.getline(buffer, size, '\n')
char p buffer0 // ref 1st
char of seq do cout ltlt "" ltlt p ltlt "" ltlt
endl p strlen(p)1 //
move to next location while ( p )
// still ref a valid char return 0
Exe a pointer to source of process in binary
file Environ A file that contains the
environment variable for the process Like cmdline
file. Fd File descriptor. A subdirectory that
contains one decimal number entry for each file
process has open. Maps A file contains the
virtual address maps for the process as well as
the access permissions to mapped regions. Root A
pointer to root filesystem for the processç Stat
A file that contains process status information
Statm A file with status of the processs
memory usage Status A file that contains much of
the same information found in stat and statm.