0% found this document useful (0 votes)
5 views

Chapter 5 Process Managment in Unix (1)

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 5 Process Managment in Unix (1)

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 5.

Managing Processes in Unix.


UNIX Processes
 A process is a program in execution.
 The process is said to be born when the program starts
execution.
 The process remains alive as long as the program is active.
 The process is said to be dead when the program completes
execution.
 Usually, the name of the process is same as the name of the
program being executed. For ex: A process named grep is
created when grep command is being executed.
 The processes have attributes. (just like files).
 Two important attributes of a process:
 1) The Process-Id (PID)
 PID is a unique integer used to identify each process uniquely.
 PID is allocated by the kernel when the process is born.
 PID can be used to control a process.
 2)The Parent PID (PPID)
 The PID of the parent is available as a process attribute.
UNIX Processes
 The kernel contains a process table with an entry that
describes the state of every active process in the system.
 The u area contains additional information that controls the
operation of a process.
 The process table entry and the u area are part of the
context of a process.
 The aspect of the process context that most visibly
distinguishes it from the context of another process is, of
course, the contents of its address space.
UNIX Processes
 A program that has started is manifested in
the context of a process.
 A process in the system is represented:
 Process Identification Elements
 Process State Information
 Process Control Information
 User Stack
 Private User Address Space, Programs and Data
 Shared Address Space
Process Control Block
 Process Information, Process State Information,
and Process Control Information constitute the
PCB.
 All Process State Information is stored in the
Process Status Word (PSW).
 All information needed by the OS to manage the
process is contained in the PCB.
 A UNIX process can be in a variety of states:
States of a UNIX Process
 User running: Process executes in user mode
 Kernel running: Process executes in kernel mode
 Ready to run in memory: process is waiting to be
scheduled
 Asleep in memory: waiting for an event
 Ready to run swapped: ready to run but requires
swapping in
 Preempted: Process is returning from kernel to user-
mode but the system has scheduled another process
instead
 Created: Process is newly created and not ready to run
 Zombie: Process no longer exists, but it leaves a
record for its parent process to collect.
Process State Transitions
kernel data structures
 Two kernel data structures describe the state of a process: the
process table entry and the u area.
 The process table contains fields that must always be accessible to
the kernel, but the u area contains fields that need to be accessible
only to the running process.
 Therefore, the kernel allocates space for the u area only when
creating a process: It does not need u areas for process table
entries that do not have processes.
 The fields in the process table are the following.
 • The state field identifies the process state.
 • The process table entry contains fields that allow the kernel to locate the
process and its u area in main memory or in secondary storage.
 The kernel uses the information to do a context switch to the
process when the process moves from state "ready to run in
memory" to the state "kernel running" or from the state
"preempted" to the state "user running."
kernel data structures
 Several user identifiers (user IDs or UIDs) determine various process
privileges.
 For example, the user ID fields delineate the sets of processes that can
send signals to each other.
 Process identifiers (process IDs or PIDs) specify the relationship of
processes to each other.
 These ID fields are set up when the process enters the state "created" in
the fork system call.
 The process table entry contains an event descriptor when the process is
in the "sleep" state.
 Scheduling parameters allow the kernel to determine the order in which
processes move to the states "kernel running" and "user running."
 A signal field enumerates the signals sent to a process but not yet
handled
 Various timers give process execution time and kernel resource
utilization, used for process accounting and for the calculation of process
scheduling priority.
 One field is a user-set timer used to send an alarm signal to a process.
The u area
 The u area contains the following fields that further characterize the process states.
 A pointer to the process table identifies the entry that corresponds to the u area.
 The real and effective user IDs determine various privileges allowed the process,
such as file access rights.
 Timer fields record the time the process (and its descendants) spent executing
in user mode and in kernel mode.
 An array indicates how the process wishes to react to signals.
 The control terminal field identifies the "login terminal" associated with the
process, if one exists,
 An error field records errors encountered during a system call.
 A return value field contains the result of system calls.
 I/O parameters describe the amount of data to transfer, the address of the
source (or target) data array in user space, file offsets for I/0, and so on.
 The current directory and current root describe the file system environment of
the process.
 The user file descriptor table records the files the process has open.
 Limit fields restrict the size of a process and the size of a file it can write.
 A permission modes field masks mode settings on files the process creates.
The Shell Process
 When a user logs into the system, the kernel
creates a shell process.
 Any command entered by the user is actually the
standard input to the shell process.
 When the user logs out of the system, the kernel
kills the shell process.
Parent and Child Process
 A process that creates another process is called the parent
process.
 A newly created process is called the child process.
 When user enters a command at the prompt($), the shell
becomes the parent process, which in turn creates a child
process.
 For example:
 1)When the command cat emp.lst is run from the keyboard, the
shell process creates a child process for running the cat
program.
 2) When commands like "cat sample.lst | grep MH student.lst" is
run from the keyboard, the shell process creates two child
processes simultaneously:
 1) one for running the cat program and
 2) another for running the grep program.
 The shell is said to be the parent of cat & grep.
Wait or not Wait?
 A parent may wait for the child to die so that the
parent can create the next process.
 The death of the child is intimated to the parent by the
kernel.
 Example: Shell process
 A parent may not wait for the child to die and may
continue to create other processes.
 Example: init process
Creating a new process
 In UNIX, a new process is created by means of the fork() -
system call.
 The OS performs the following functions:
 It allocates a slot in the process table for the new
process
 It assigns a unique ID to the new process
 It makes a copy of process image of the parent (except
shared memory)
 It assigns the child process to the Ready to Run State
 It returns the ID of the child to the parent process, and
0 to the child.

 Note, the fork() call actually is called once but returns


twice - namely in the parent and the child process.
Fork()
 Pid_t fork(void) is the prototype of the fork() call.
 Remember that fork() returns twice
 in the newly created (child) process with return value 0
 in the calling process (parent) with return value = pid of
the new process.
 A negative return value (-1) indicates that the call has
failed
 Different return values are the key for
distinguishing parent process from child process!
 The child process is an exact copy of the parent,
yet, it is a copy i.e. an identical but separate
process image.
Fork()
 The parent process uses fork() to create a child process.
 After fork() executes, the parent & child have different PIDs and PPIDs.
 When fork is invoked, the kernel replicates address space of the parent
process to the child process.
 When a process is forked, the child inherits following attributes of the
parent.
 User name of the real and effective user (RUID and EUID).
 Real and effective group owner (RGID and EGID).
 The current directory from where the process was run.
 The file descriptors of all files opened by the parent process.
 Environment variables like HOME, PATH.
 '.' child runs in its own address space, changes made to these parameters
don't affect the parent.
 Forking process is responsible for the multiplication of processes in the
system.
 At this point, both parent & child continue execution at the statement
following fork.
A fork() Example
#include <unistd.h>
main()
{
pid_t pid /* process id */
printf(“just one process before the fork()\n”);
pid = fork();
if(pid == 0)
printf(“I am the child process\n”);
else if(pid > 0)
printf(“I am the parent process\n”);
else
printf(“DANGER - the fork() has failed\n”)
}
Basic Process Coordination
 Exec
 Forking only creates a process but it doesn't execute a
new program.
 The child process uses exec() to execute its own new
program.
 This operation replaces the entire address space with that
of the new program.
 The PID and PPID of the child remains unchanged.
 At the end of the execution, exit() is called to terminate
the child.
Basic Process Coordination
 The exit() call is used to terminate a process.
 Its prototype is: void exit(int status), where status is used
as the return value of the process.
 exit(i) can be used to announce success and failure to the
calling process.

 The wait() call is used to temporarily suspend the


parent process until one of the child processes
terminates.
 The prototype is: pid_t wait(int *status), where status is a
pointer to an integer to which the child’s status
information is being assigned.
 wait() will return with a pid when any one of the children
terminates or with -1 when no children exist.
Example
When command ls is entered from the keyboard, shell performs following tasks:
The shell calls fork(). This creates a new process to run the ls program.
The ls process calls exec(). This replaces the shell program with the ls program
and then starts executing the ls program.
The ls program performs its task. In the meanwhile, the shell executes wait().
The entire mechanism of process creation is pictorially shown below:
more coordination
 To wait for a particular child process to terminate,
we can use the waitpid() call.
 Prototype: pid_t waitpid(pid_t pid, int *status, int opt)

 Sometimes we want to get information about the


process or its parent.
 getpid() returns the process id
 getppid() returns the parent’s process id
 getuid() returns the users id
 use the manual pages for more id information.
ps
 Two of the shell commands that you will be using when working
with processes are ps and kill.
 This command is used to display the attributes of processes
that are running currently.
 This command reads through the kernel’s process tables to
fetch the attributes of processes.
 By default, this command displays the process owned by the
user running the command.
 ps reports on active processes.
• -A lists all processes
• -e includes the environment
• -u username, lists all processes associated with
username
 NOTE: the options may be differ on different systems!!
 If user execute the ps command immediately after logging
in, will display the following details.
ps
 Example:
$ ps
PID TTY TIME CMD
4245 pts/7 00:00:00 bash
5314 pts/7 00:00:00 ps

 The header includes the following information:


 PID – Process Identification number
 TTY – terminal with which the process is associated
 Time - CPU time taken by the process
 CMD – Process name.
ps Options
 Full Listing (-f)
 –f (full) option can be used to get a detailed list of attributes of all
processes including parent processes.
 Example:
$ ps -f
UID PPID STIME TTY TIME COMMAND
PID
C
root 14931 136 0 08:37:48 ttys 0 0:00 rlogind
sps 14932 14931 0 08:37:50 ttys 0 0:00 -sh
 The header includes the following information:
 UID – Login name of the user
 PID – Process ID
 PPID – Parent process ID
 C – An index of recent processor utilization, used by kernel for scheduling
 STIME – Starting time of the process in hours, minutes and seconds
 TTY – Terminal ID number
 TIME – Cumulative CPU time consumed by the process
 CMD – The name of the command being executed
ps Options
 Displaying Processes of a User (-u)
 –u (user) option can be used to know the activities of any user.
 Example:
$ ps -u kumar

 Displaying All User Processes (-a)


 –a (all) option can be used to display all user processes. However, it
doesn’t display the system- processes.
 Example:
$ ps -a PID
TTY TIME CMD
705 pts/05 00:00:00 sh
785 pts/09 00:00:03 vi
ps Options
 System Processes (-e)
 In addition to the user processes, a no. of system-processes
keep running all the time in the system.
 Most system-processes are not associated with any
controlling terminal (Ex: pts/01).
 System-processes are created
 → during system startup or
 → when the system goes into multiuser mode.
 System-processes are known as daemons because they are
called w/o a specific request from a user.
 –e (every) option can be used to display all processes
including both user & system processes.
 Example:
$ ps –e PID
TTY TIME CMD
1 ? 41:55 init
234 0:03 sh
pts/08
 In the TTY column, ? indicates system processes which don’t
have a controlling terminal.
Executing a Command at a Specified Point
of Time: at Command
 UNIX provides facilities to schedule a job to run at a specified time
of day.
 The user can schedule least important jobs at a time when the
system load is low.
 Job scheduling can be done using 2 commands:
1) at and 2) batch.

 at: One-Time Execution


 This command
→ takes the time the job is to be executed as its argument and
→ displays the at> prompt.
 Input has to be given from the standard input (keyboard).
 Syntax:
at [hh:mm] [am/pm] [now/noon/midnight/today/tomorrow]
Executing a Command at a Specified Point
of Time: at Command
 at: One-Time Execution
 Example: $ at 12:00
at > emp.sh
[ctrl-d]
Commands will be executed using /usr/bin/sh
Job 1 at Sat Nov 5 12:00:00: 2020

 Here, the job goes to the queue known as "at queue".


 At 12:00 a.m, the script file emp.sh will be executed.
 The output shows job number, the date and time of scheduled execution.
 We can also use the –f option to take the input from the file.
 Example: $ at -f scriptfile 7 am Monday
$ at 10:23 Friday
at > lp /usr/sales/reports/*
at > echo “Files printed,!” | mail -s ”Job done” boss
[Ctrl-d]

 The above job


 → prints all files in the directory /usr/sales/reports and
 → notifies the user named boss that the job is done
Executing a Command at a Specified Point
of Time: batch: Execute in Batch Queue
 batch: Execute in Batch Queue
 This command allows the operating system to decide an
appropriate time to run a process.
 This command can be used to schedule jobs for later execution.
 The jobs are executed as soon as the system load permits.
 This command uses an internal algorithm to determine the
execution time.
 Example: $ batch < emp.sh
Commands will be executed using /usr/bin/bash
Job 34 at sun dec 8 12:34:12 2008

 Example: $ batch
sort /usr/sales/reports/* | lp
echo “Files printed, Boss!” | mailx -s ”Job done” boss

 The above job


 → sorts a collection of files
 → prints the results and notifies the user named boss that the job is done.
nice
 Processes are sequentially assigned resources for execution.
 The kernel assigns the CPU to a process for a duration of time (called time slice).
 When the time elapses, the process is placed in a queue.
 The execution of processes is scheduled depending on the priority assigned to the
process.
 The nice command is used to control background process dispatch priority.
 The nice command is used with & operator to reduce the priority of processes.
 The main idea of nice: background processes must demand less attention from the
system than interactive processes.
 nice values are system dependent and typically range from 1 to 19.
 A high nice value implies a lower priority.
 The lower the nice number, the more important a job is and the more resources it will
take without sharing them.
 Example:
 $ nice wc –l hugefile.txt
nice
 Changing priority of Process (-n)

 The user can specify the nice value explicitly with –n (number)

option where number is an offset to the default.

 The priority is increased by that number up to a limit of 20.

 Example:

$ nice –n 5 wc –l hugefile.txt & ;nice value increased by 5

unit
Background Processes
 When you start a process (run a command), there
are two ways you can run it:
 Foreground Processes
 By default, every process that you start runs in
the foreground. It gets its input from the keyboard
and sends its output to the screen.
Background Processes
 Background Processes
 A background process runs without being connected to your
keyboard.
 If the background process requires any keyboard input, it
waits.
 The advantage of running a process in the background is that
you can run other commands; you do not have to wait until it
completes to start another!
 There can be only one job in the foreground, the remaining
jobs have to run in the background.
 There are two ways of starting a job in the background:
 with the shell’s & operator
 nohup command.
Background Processes
 & : No Logging out
 The & is the shell’s operator used to run a process in the background.
 The user can direct the shell to execute the command in the background.
 In this case, the parent doesn’t wait for the child’s termination.
 Example:

$ sort –o emp.dat emp.dat &

[1] 1413 The job’s PID


 Here, the shell immediately returns a PID(1413) of the invoked
command.
 The prompt is returned($).
 The shell is ready to accept the next command even though the previous
command has not been terminated yet.
 The shell remains the parent of the background process.
Background Processes
 nohup
 nohup statement can be prefixed to a command to permit execution of the process even
after the user has logged out.
 Here also, the shell operator & must be used.
 Synyax:

nohup command-string [input-file] output-file &


 Example:

$ nohup sort emp.lst &

1252 Sending output to nohup.out


 Here, the shell immediately returns a PID(1252) of the invoked command.
 nohup sends the standard output(or error) of the command to the file nohup.out.
 When the user logs out, the child becomes an orphan and the init process becomes
parent of orphan.
 In this case, the kernel reassigns the PPID of the orphan to the system’s init process (PID
1).
 In this way, the user can terminate a parent (the shell) without terminating its child.
bg and fg Commands
 A job refers to a group of processes that are created by
combining a set of commands(Eg: ls | wc).
 Examples of Job control:
 Move a job to the background (bg)
 Bring the job back to the foreground (fg)
 List the active jobs (jobs)
 Suspend a foreground job ([Ctrl-z])
 Kill a job (kill)
bg and fg Commands
 bg
 This command can be used to move currently running foreground process to
run in background.
 Syntax:
bg [PID...] OR bg %jobname
 Example: $ bg // moves current job to
[2] + sh1.sh &background
+ symbol indicates > Current job
- symbol indicates > Previous job
$ bg %0 // moves job with id 0 to background
$ bg %sort // moves sort process to background
 fg
 This command can be used to move currently running background process to
run in foreground.
fg %jobno OR fg %jobname
 Example: $ fg // brings most recent background process
$ fg %2 // brings 2nd background process to foreground
$ fg %sort // brings sort process to foreground
Signals
 Signals are software interrupts sent to a program to
indicate that an important event has occurred.
 The events can vary from user requests to illegal
memory access errors.

Signal Name Signal Description


Number
SIGHUP 1 Hang up detected on controlling terminal or death of controlling process
SIGINT 2 Issued if the user sends an interrupt signal (Ctrl + C)
SIGQUIT 3 Issued if the user sends a quit signal (Ctrl + D)
SIGKILL 9 If a process gets this signal it must quit immediately
SIGTERM 15 Software termination signal (sent by kill by default)
kill and killall
 Terminating a process prematurely is called killing.
 The kill command can be used to terminate a background process.
 <ctrl-c> can be used to terminate a foreground process.
 In order to communicate with an executing process from the shell, you must send a
signal to that process.
 The kill command sends a signal to the process.
 You can direct the signal to a particular process by using its pid
 The kill command has the following format:
 kill [options] pid
 -l lists all the signals you can send
 -p (on some systems prints process informantion)
 -signal is a signal number
 Syntax:
 kill PIDs OR kill –s NUMBER
 Example:
 $ kill 123 // To kill a process whose PID is 123
 $ kill 123 342 73 // To kill several processes whose PIDs are 123, 342, and 73
 Kill command uses SIGTERM (15) as default signal for terminating a process.
 The programs can send/receive more than 20 signals, each of which is represented by a
number.
more on kill
 Killing the last background Job
 $! : stores the PID of the last background job.
 Example:
 $ Sort -o emp.lst emp8.lst &
 $ kill $!
 Killing the login shell
 $$ --- Stores PID of the current shell.
 Example:
 $ kill -9 $$ OR kill -s KILL 0 (Kills all process including login
shell)
 Using kill with other Signals
 If the process ignores the signal SIGTERM, the user can
terminate with SIGKILL signal (9).
 Example:
 $ kill -9 123 OR $ kill –s KILL 123
find
 This command
 → recursively examines a directory tree to look for files matching some criteria and
 → then takes some action on the selected files.
 Syntax:
 find path_list selecton_criteria action
 Here, path_list consists of one or more directories to be examined selection-
criteria contains conditions used for matching a file action specifies some
action to be taken on the selected files
 Example:
 $find / -name a.out -print // locates all files named a.out
 /home/kumar/a.out
 /home/user/a.out
 Here,
 path_list / indicates that the search should start from root directory.
 Then, each file in the list is matched against the selection criteria.
 The selection criteria always consists of an expression in the form –operator
argument.
 If the expression matches the file, the file is selected.
 Finally, a display selected files on the terminal.

You might also like