52631387 mc0070 operating system

Upload: jyothi-rao

Post on 07-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 52631387 MC0070 Operating System

    1/25

    Master of Computer Application (MCA) Semester 2

    MC0070 Operating Systems with UNIX

    Assignment Set 1

    Que 1. 1. Describe the following operating systemcomponents:

    A)Functions of an Operating system B) Operating

    system components

    Ans:

    Functions of an Operating System

    Modern Operating systems generally have following three major goals. Operating systemsgenerally accomplish these goals by running processes in low privilege and providingservice calls that invoke the operating system kernel in high-privilege state.

    (1)To hide details of hardware

    An abstraction is software that hides lower level details and provides a set of higher-levelfunctions. An operating system transforms the physical world of devices, instructions,memory, and time into virtual world that is the result of abstractions built by the operatingsystem. There are several reasons for abstraction.

    First, the code needed to control peripheral devices is not standardized. Operating systemsprovide subroutines called device drivers that perform operations on behalf of programs forexample, input/output operations.

    Second, the operating system introduces new functions as it abstracts the hardware. Forinstance, operating system introduces the file abstraction so that programs do not have to

    deal with disks.

    Third, the operating system transforms the computer hardware into multiple virtualcomputers, each belonging to a different program. Each program that is running is called a

    process. Each process views the hardware through the lens of abstraction.

    Fourth, the operating system can enforce security through abstraction.

    1

  • 8/4/2019 52631387 MC0070 Operating System

    2/25

    (2) Resources Management

    An operating system as resource manager, controls how processes (the active agents) mayaccess resources (passive entities). One can view Operating Systems from two points ofviews: Resource manager and Extended machines. Form Resource manager point of

    view Operating Systems manage the different parts of the system efficiently and fromextended machines point of view Operating Systems provide a virtual machine to users thatis more convenient to use. The structurally Operating Systems can be design as amonolithic system, a hierarchy of layers, a virtual machine system, a micro-kernel, or usingthe client-server model. The basic concepts of Operating Systems are processes, memorymanagement, I/O management, the file systems, and security.

    (3) Provide a effective user interface

    The user interacts with the operating systems through the user interface and usually

    interested in the look and feel of the operating system. The most important components ofthe user interface are the command interpreter, the file system, on-line help, and applicationintegration. The recent trend has been toward increasingly integrated graphical userinterfaces that encompass the activities of multiple processes on networks of computers.

    Operating System Components

    Many modern operating systems share the same goal of supporting thefollowing types of system components.

    (1). Process Management

    The operating system manages many kinds of activities ranging from user programs tosystem programs like printer spooler, name servers, file server etc. Each of these activitiesis encapsulated in a process. A process includes the complete execution context (code, data,PC, registers, OS resources in use etc.).

    a process is not a program. A process is only ONE instant of a program in execution. Thereare many processes can be running the same program. The five major activities of anoperating system in regard to process management are

    1. Creation and deletion of user and system processes.

    2. Suspension and resumption of processes.

    3. A mechanism for process synchronization.

    4. A mechanism for process communication.

    5. A mechanism for deadlock handling

    2

  • 8/4/2019 52631387 MC0070 Operating System

    3/25

    (2) Main-Memory Management

    (1) Primary-Memory or Main-Memory is a large array of words or bytes. Each word orbyte has its own address. Main-memory provides storage that can be access directly bythe CPU. That is to say for a program to be executed, it must in the main memory.

    (2) The major activities of an operating in regard to memory-management are:(3) 1. Keep track of which part of memory is currently being used and by whom.(4) 2. Decide which processes are loaded into memory when memory space becomes

    available.(5) 3. Allocate and de-allocate memory space as needed.

    (3) File Management

    A file is a collection of related information defined by its creator. Computer canstore files on the disk (secondary storage), which provides long term storage. Someexamples of storage media are magnetic tape, magnetic disk and optical disk. Each of thesemedia has its own properties like speed, capacity, data transfer rate and access methods.

    A file system normally organized into directories to ease their use. These directoriesmay contain files and other directions.

    The five main major activities of an operating system in regard to file managementare

    1. The creation and deletion of files.

    2. The creation and deletion of directions.

    3. The support of primitives for manipulating files and directions.

    4. The mapping of files onto secondary storage.

    5. The back up of files on stable storage media.

    (4). I/O System Management

    I/O subsystem hides the peculiarities of specific hardware devices from the user.Only the device driver knows the peculiarities of the specific device to whom it is assigned

    (5). Secondary-Storage Management

    3

  • 8/4/2019 52631387 MC0070 Operating System

    4/25

    Generally speaking, systems have several levels of storage, including primarystorage, secondary storage and cache storage. Instructions and data must be placed in

    primary storage or cache to be referenced by a running program. Because main memory istoo small to accommodate all data and programs, and its data are lost when power is lost,the computer system must provide secondary storage to back up main memory. Secondary

    storage consists of tapes, disks, and other media designed to hold information that willeventually be accessed in primary storage (primary, secondary, cache) is ordinarily dividedinto bytes or words consisting of a fixed number of bytes. Each location in storage has anaddress; the set of all addresses available to a program is called an address space.

    The three major activities of an operating system in regard to secondary storagemanagement are:

    1. Managing the free space available on the secondary-storage device.

    2. Allocation of storage space when new files have to be written.

    3. Scheduling the requests for memory access.

    (5). Networking

    A distributed system is a collection of processors that do not share memory,peripheral devices, or a clock. The processors communicate with one another throughcommunication lines called network. The communication-network design must consider

    routing and connection strategies, and the problems of contention and security.

    (6). Protection System

    If a computer system has multiple users and allows the concurrent execution of multiple processes, then various processes must be protected from one anothers activities.Protection refers to mechanism for controlling the access of programs, processes, or usersto the resources defined by a computer system.

    (7). Command Interpreter System

    A command interpreter is an interface of the operating system with the user. The user givescommands with are executed by operating system (usually by turning them into systemcalls). The main function of a command interpreter is to get and execute the next userspecified command. Command-Interpreter is usually not part of the kernel, since multiplecommand interpreters (shell, in UNIX terminology) may be supported by an operating

    4

  • 8/4/2019 52631387 MC0070 Operating System

    5/25

    system, and they do not really need to run in kernel mode. There are two main advantagesof separating the command interpreter from the kernel.

    1. If we want to change the way the command interpreter looks, i.e., I want to change theinterface of command interpreter, I am able to do that if the command interpreter is separate

    from the kernel. I cannot change the code of the kernel so I cannot modify the interface.

    2. If the command interpreter is a part of the kernel, it is possible for a malicious process togain access to certain part of the kernel that it should not have. To avoid this scenario it isadvantageous to have the command interpreter separate from kernel.

    Que 2. Describe the following:

    A. Micro Kernels

    B. Modules

    Ans:

    A.Micro-kernels

    We have already seen that as UNIX expanded, the kernel became large and difficult tomanage. In the mid-1980s, researches at Carnegie Mellon University developed anoperating system called Mach that modularized the kernel using the microkernel approach.This method structures the operating system by removing all nonessential components fromthe kernel and implementing then as system and user-level programs. The result is a smallerkernel. There is little consensus regarding which services should remain in the kernel and

    which should be implemented in user space. Typically, however, micro-kernels provideminimal process and memory management, in addition to a communication facility.

    5

    Device

    Drivers

    FileServer

    ClientProcess

    . VirtualMemory

    Microkernel

    Hardware

  • 8/4/2019 52631387 MC0070 Operating System

    6/25

    Fig. Microkernel Architecture

    The main function of the microkernel is to provide a communication facilitybetween the client program and the various services that are also running in user space.Communication is provided by message passing. For example, if the client program andservice never interact directly. Rather, they communicate indirectly by exchangingmessages with the microkernel.

    On benefit of the microkernel approach is ease of extending the operating system.All new services are added to user space and consequently do not require modification of

    the kernel. When the kernel does have to be modified, the changes tend to be fewer,because the microkernel is a smaller kernel. The resulting operating system is easier to portfrom one hardware design to another. The microkernel also provided more security andreliability, since most services are running as user rather than kernel processes, if aservice fails the rest of the operating system remains untouched.

    Several contemporary operating systems have used the microkernel approach.Tru64 UNIX (formerly Digital UNIX provides a UNIX interface to the user, but it isimplemented with a March kernel. The March kernel maps UNIX system calls intomessages to the appropriate user-level services.

    The following figure shows the UNIX operating system architecture. At the centeris hardware, covered by kernel. Above that are the UNIX utilities, and command interface,such as shell (sh), etc

    6

  • 8/4/2019 52631387 MC0070 Operating System

    7/25

    Fig. UNIX Architecture

    B. Modules

    Perhaps the best current methodology for operating-system design involves using object-oriented programming techniques to create a modular kernel. Here, the kernel has a set ofcore components and dynamically links in additional services either during boot time orduring run time. Such a strategy uses dynamically loadable modules and is common inmodern implementations of UNIX, such as Solaris, Linux and MacOSX. For example, theSolaris operating system structure is organized around a core kernel with seven types ofloadable kernel modules:

    1. Scheduling classes

    2. File systems

    3. Loadable system calls

    4. Executable formats

    5. STREAMS formats

    6. Miscellaneous

    7. Device and bus drivers

    7

  • 8/4/2019 52631387 MC0070 Operating System

    8/25

    Such a design allow the kernel to provide core services yet also allows certain features to beimplemented dynamically. For example device and bus drivers for specific hardware can beadded to the kernel, and support for different file systems can be added as loadablemodules. The overall result resembles a layered system in that each kernel section hasdefined, protected interfaces; but it is more flexible than a layered system in that any

    module can call any other module. Furthermore, the approach is like the microkernelapproach in that the primary module has only core functions and knowledge of how to loadand communicate with other modules; but it is more efficient, because modules do not needto invoke message passing in order to communicate.

    .

    Que 3. Describe the concept of process control inOperating systems.

    Ans:

    Process Control

    In this section we will study structure of a process, process control block, modes of process

    execution, and process switching.

    Process Structure

    After studying the process states now we will see where does the process reside, and whatis the physical manifestation of a process?

    The location of the process depends on memory management scheme being used. In thesimplest case, a process is maintained in the secondary memory, and to manage this

    process, at least small part of this process is maintained in the main memory. To executethe process, the entire process or part of it is brought in the main memory, and for that theoperating system need to know the location of the process.

    Process identification

    Processor state information

    Process control information

    User StackPrivate user address space (program,

    8

  • 8/4/2019 52631387 MC0070 Operating System

    9/25

    data)

    Shared address space

    Figure: Process Image

    The obvious contents of a process are User Program to be executed, and the UserDatawhich is associated with that program. Apart from these there are two major parts of a

    process; System Stack, which is used to store parameters and calling addresses forprocedure and system calls, and Process Control Block, this is nothing but collection ofprocess attributes needed by operating system to control a process. The collection of userprogram, data, system stack, and process control block is called as Process Image as shownin the figure 3.3 above.

    Process Control Block

    A process control block as shown in the figure 3.4 bellow, contains various attributesrequired by operating system to control a process, such as process state, program counter,CPU state, CPU scheduling information, memory management information, I/O stateinformation, etc.

    These attributes can be grouped in to three general categories as follows:

    Process identification

    Processor state information

    Process control information

    The first category stores information related to Process identification, such as identifier ofthe current process, identifier of the process which created this process, to maintain parent-child process relationship, and user identifier, the identifier of the user on behalf of whosthis process is being run.

    The Processor state information consists of the contents of the processor registers, such asuser-visible registers, control and status registers which includes program counter and

    program status word, and stack pointers.

    The third category Process Control Identification is mainly required for the control of aprocess. The information includes: scheduling and state information, data structuring, inter-process communication, process privileges memory management, and resource ownershipand utilization.

    pointer process state

    process number

    9

  • 8/4/2019 52631387 MC0070 Operating System

    10/25

    program counter

    registers

    memory limits

    list of open files

    .

    .

    .

    Figure: Process Control Block

    Modes of Execution

    In order to ensure the correct execution of each process, an operating system must protecteach processs private information (executable code, data, and stack) from uncontrolledinterferences from other processes. This is accomplished by suitably restricting the memoryaddress space available to a process for reading/writing, so that the OS can regain CPUcontrol through hardware-generated exceptions whenever a process violates thoserestrictions.

    Also the OS code needs to execute in a privileged condition with respect to normal: tomanage processes, it needs to be enabled to execute operations which are forbidden tonormal processes. Thus most of the processors support at least two modes of execution.Certain instructions can only be executed in the more privileged mode. These include

    reading or altering a control register such as program status word, primitive I/O instruction;and memory management instructions.

    The less privileged mode is referred as user mode as typically user programs are executedin this mode, and the more privileged mode in which important operating system functionsare executed is called as kernel mode/ system mode or control mode.

    The current mode information is stored in the PSW, i.e. whether the processor is running inuser mode or kernel mode. The mode change is normally done by executing change modeinstruction; typically after a user process invokes a system call, or whenever an interruptoccurs, as these are operating system functions and needed to be executed in privileged

    mode. After the completion of system call or interrupt routine, the mode is again changed touser mode to continue the user process execution.

    Context Switching

    To give each process on a multiprogrammed machine a fair share of the CPU, a hardwareclock generates interrupts periodically. This allows the operating system to schedule all

    processes in main memory (using scheduling algorithm) to run on the CPU at equal

    intervals. Each time a clock interrupt occurs, the interrupt handler checks how much timethe current running process has used. If it has used up its entire time slice, then the CPU

    10

  • 8/4/2019 52631387 MC0070 Operating System

    11/25

    scheduling algorithm (in kernel) picks a different process to run. Each switch of the CPUfrom one process to another is called a context switch.

    A context is the contents of a CPUs registers and program counter at any point in time.Context switching can be described as the kernel (i.e., the core of the operating system)

    performing the following activities with regard to processes on the CPU: (1) suspending theprogression of one process and storing the CPUs state (i.e., the context) for that processsomewhere in memory, (2) retrieving the context of the next process from memory andrestoring it in the CPUs registers and (3) returning to the location indicated by the programcounter (i.e., returning to the line of code at which the process was interrupted) in order toresume the process. The figure 3.5 bellow depicts the process of context switch from

    process P0 to process P1.

    Figure: Process switching

    11

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image00632.jpg
  • 8/4/2019 52631387 MC0070 Operating System

    12/25

    Que.4. Describe the following with respect to UNIXoperating System:A) Hardware ManagementB) Unix Architecture

    Ans:

    Hardware Management

    One of the first things you do, after successfully plugging together a plethora of cables andcomponents, is turn on your computer. The operating system takes care of all the starting

    functions that must occur to get your computer to a usable state. Various pieces of hardwareneed to be initialized. After the start-up procedure is complete, the operating system awaitsfurther instructions. If you shut down the computer, the operating system also has a

    procedure that makes sure all the hardware is shut down correctly. Before turning yourcomputer off again, you might want to do something useful, which means that one or moreapplications are executed. Most boot ROMs do some hardware initialization but not much.Initialization of I/O devices is part of the UNIX kernel.

    To perform its task, a process may need to access hardware resources. The process mayneed to read or write to a file, send data to a network card (to communicate with anothercomputer), or send data to a printer. The operating system provides such services for the

    process. This is referred to as resource allocation. A piece of hardware is a resource, and theoperating system allocates available resources to the different processes that are running.See Table 1.1 for a summary of different actions and what the operating system (OS) doesto manage them.

    Table 1.1. Operating system functions

    Action OS Does This

    You turn on the computer Hardware management

    You execute an application Process management

    Application reads a tape Hardware managementApplication waits for data Process management

    Process waits while other process runsProcess management

    Process displays data on screen Hardware management

    Process writes data to tape Hardware management

    You quit, the process terminates Process management

    You turn off the computer Hardware management

    From the time you turn on your computer until you turn it off, the operating system is

    coordinating the operations. As hardware is initialized, accessed, or shut down, theoperating system manages these resources. As applications execute, request, and receive

    12

  • 8/4/2019 52631387 MC0070 Operating System

    13/25

    resources, or terminate, the operating system takes care of these actions. Without anoperating system, no application can run and your computer is just an expensive

    paperweight.

    UNIX Architecture

    At the center of the UNIX onion is a program called the kernel. It is absolutelycrucial to the operation of the UNIX system. The kernel provides the essential services thatmake up the heart of UNIX systems; it allocates memory, keeps track of the physicallocation of files on the computers hard disks, loads and executes binary programs such asshells, and schedules the task swapping without which UNIX systems would be incapableof doing more than one thing at a time.

    The kernel accomplishes all these tasks by providing an interface between the otherprograms running under its control and the physical hardware of the computer; thisinterface, the system call interface, effectively insulates the other programs on theUNIX system from the complexities of the computer. For example, when a running

    program needs access to a file, it cannot simply open the file; instead it issues asystem call which asks the kernel to open the file. The kernel takes over and handlesthe request, then notifies the program whether the request succeeded or failed. Toread data in from the file takes another system call; the kernel determines whether

    or not the request is valid, and if it is, the kernel reads the required block of data andpasses it back to the program. Unlike DOS (and some other operating systems),

    13

  • 8/4/2019 52631387 MC0070 Operating System

    14/25

    UNIX system programs do not have access to the physical hardware of thecomputer. All they see are the kernel services, provided by the system call interface.

    Although there is a well-defined, technical and commercial standard for whatconstitutes Unix, in common usage, Unix refers to a set of operating systems, from

    private vendors

    and in various open-licensed versions, that act similarly from the view of users andadministrators. Within any Unix version, there are several different shells which affecthow commands are interpreted. Your default is that you are using Solaris (developed bySun Microsystems primarily for use on hardware sold by Sun) within the c-shell. Most ofthe basic commands here will work the same in other Unix variants and shells, includingLinux and the Mac OS X command-line environment

    A standard Unix system provides commands username, passwd, chsh, and

    additional options on chdgrp to change usernames, passwords, default groups,

    and shell environments.

    Wildcards: * is a wildcard character that can refer to any character string and ? is awildcard character that can refer to any single character. E.g., mv *.f95 code would move

    every Fortran 95 program file on the current directory into a subdirectory called code.Filenames: in our version of Unix, they may be up to 255 characters, and they may includeany character except the regular slash /. (Avoid using backslashes, blank spaces, ornonprinting characters in filenames they are allowed but will cause problems for you.)

    A pathname beginning with / is an absolute path from the top of the system tree. Apathname not beginning with / is a relative path down from the current working directory.

    Directory shortcuts include: as a replacement for your home directory, username as ashorthand for usernames home directory, .. (two periods) for the subdirectory one level upfrom the current directory, and . (one period) for the current directory.

    Que .5. Describe the following:

    A) Unix KernelB) Unix Startup Scripts

    Ans:

    Kernel

    Most Unix systems implement a two-stage loading process: During the first stage, asmall boot program is read into memory from a default or specified device. It is this

    program that reads in the kernel and relinquishes the control to it. The path to the kernel is

    14

  • 8/4/2019 52631387 MC0070 Operating System

    15/25

    vendor-dependent. For example, it is /vmunix on SunOS 4.x, Digital Unix and Ultrix,/kernel/unix on SunOS 5.x, or /unix on IRIX and AIX systems. Once the kernel is loaded, itremains in the memory during the running of the system.

    The kernel probes the bus to locate the devices specified during the configuration,

    and initializes the located devices (ignoring those that it cant contact). Any device notdetected and initialized during the boot will not be accessible to system until it is properlyconnected and the system is rebooted.

    System Processes

    The kernels identifies the root, swap, and dump devices and then starts programs toschedule processes, manage physical memory and virtual memory, and the init process.BSD systems starts three initialization processes; swapper, init and pagedaemon. On theSVR4 systems the initialization processes include sched, init, and various memory handlers(except on Solaris).

    sched: The real-time scheduler, sched, runs as process 0 on SVR5 systems. It can be used toset priority for real-time processes so that they can be given fast access to the kernel.

    swapper: The swapper daemon runs as process 0 on BSD systems. It manages the physicalmemory by moving process from physical memory to swap space when more physicalmemory is needed.

    page daemon: Various memory handlers run as process 2. When a page of virtual memoryis accessed, the page table within the kernel is consulted and if necessary, the pagedaemon

    (SunOS 4.x) or pageout (SunOS 5.x) is used to move pages in and out of physical memoryand to update page tables. Similar memory handlers exist on other SVR5 systems.

    init: The last step in bootstrapping the kernel starts the /etc/init process. The init processruns as process 1 and always remains in the background when the system is running. If thesystem is brought up in a single user mode, init merely creates a shell on the system console(/dev/console) and waits for it to terminate before running other startup scripts.

    Single User Mode

    Single user shell is always Bourne shell (sh) and it runs as root.

    It enables the system manager to perform various administrative functions, such as settingthe date, checking the consistency of the file system, reconfiguring the list of on-lineterminals, and so on. At this stage only the root partition is usually mounted.

    Other file systems will have to be mounted manually to use programs that do not reside onthe root volume. The file system consistency check may be performed by the commandfsck, usually found in the /etc directory.

    Startup Scripts:-

    15

  • 8/4/2019 52631387 MC0070 Operating System

    16/25

    The startup scripts are merely shell scripts, so init spawns a copy of sh to interpretthem. The startup scripts are defined and organized differently on different systems. OnBSD systems the startup scripts may be found in the /etc directory and their names beginwith rc, e.g., /etc/rc.boot, /etc/rc.single, /etc/rc.local and so on. SVR5 systems definevarious run levels in which a specific set of processes are allowed to run. This set of

    processes is defined in the /etc/inittab file. Each line in the inittab file describes an action totake. The syntax of inittab entries is:

    id:run-level:action:process

    id uniquely identifies the entry. It may be a one or characters string.

    run-level defines the run level in which the entry can be processed. If this field is empty, allrun levels are assumed.

    action identifies what actions to take for this entry. These actions may include:

    sysinit perform system initialization,

    wait wait for the process to complete,

    once run the process only once,

    respawn restart the process whenever it dies.

    process specifies the shell command to be run, if the entrys run level matches the run

    level, and/or the action field indicates such action.

    In general, the following tasks are performed in the startup scripts.

    Set the hostname.

    Set the time zone.

    Run the file system consistency check.

    Mount the systems disk partitions.

    Start the daemons and network services.

    Configure the network interface.

    Turn on the accounting and quotas.

    Shutdown

    Shutdown command:

    Notifies users with wall about the system going down. Sleeps for a minute and may give 1or 2 more reminders.

    16

  • 8/4/2019 52631387 MC0070 Operating System

    17/25

    Sends signals to all processes so they can terminate normally.

    Logs users off and kills remaining processes.

    Unmounts all secondary file system.

    Writes information about the file system status to disk to preserve the integrity.

    Notify users to reboot or to power shut down.

    Handling user account

    Any user that wants to use Unix system must have a login name or usernamedefined to the system. This login name identifies the user. When a newuser is added to unixsystems systems administrator assigns it a unique login name which is associated with anumber called UID or user identification number. This UID is the systems way of

    identifying the user. Typically, a newuser is also assigned to a group, group is collection ofusers in one department or working on one project identified with one group name. Eachgroup is identified with its GID number or group identification number.

    The user name is a short alphanumeric character string and the UID is a small positiveinteger So together UID and GID determine what kind of access rights a user has to filesand directories.

    Procedures to add a new user to system:

    Get users name and create a login id based on name, decide which group and which othergroups user need.

    Enter this data into /etc/passwd file and /etc/group file.

    Assign a password to this account, also set password aging, account expiration date,resource limits and privileges.

    Create a home directory for user, preferably on the same disk where other homedirectories exist.

    chown and cghrp to give new user ownership of his home directory.

    Set umask for new files that are created, set disk quota, mail and printing system for newuser.

    Test this account.

    USERADD: Enables a super user or root to create a new user or updates default new userinformation.

    useradd [-c comment] [-d home_dir] [-e expire_date]

    [-f inactive_time] [-g initial_group] [-G group[,...]]

    17

  • 8/4/2019 52631387 MC0070 Operating System

    18/25

    [-m [-k skeleton_dir]] [-p passwd] [-s shell]

    [-u uid [ -o]] login

    useradd -D [-g default_group] [-b default_home]

    [-f default_inactive] [-e default_expire_date]

    [-s default_shell] login

    -c comment: The new users password file comment field.

    -d home_dir: The new user will be created using home_dir as the value for the users logindirectory.

    -e expire_date: The date on which the user account will be disabled. The date is specified in

    the format YYYY-MM-DD.

    -f inactive_time: The number of days after a password expires until the account is permanently disabled. A value of 0 disables the account as soon as the password hasexpired, and a value of -1 disables the feature. The default value is -1.

    -g initial_group: The group name or number of the users initial login group. The groupname must exist. The default group no. is 1.

    -G group,[,...]: A list of supplementary groups which the user is also a member of. Each

    group is separated from the next by a comma, with no intervening whitespace.

    -m: The users home directory will be created if it does not exist. The files contained inskeleton_dir will be copied to the home directory if the -k option is used, otherwise the filescontained in /etc/skel will be used instead.

    -p passwd: The encrypted password, as returned by crypt. The default is to disable theaccount.

    -s shell: The name of the users login shell. The default is to leave this field blank, whichcauses the system to select the default login shell.

    -u uid: The numerical value of the users ID. This value must be unique, unless the -ooption is used. The value must be non-negative. The default is to use the smallest ID valuegreater than 99 and greater than every other user. Values between 0 and 99 are typicallyreserved for system accounts.

    -b default_home: The initial path prefix for a new users home directory. The users namewill be affixed to the end of default_home to create the new directory name if the -d optionis not used when creating a new account.

    -e default_expire_date: The date on which the user account is disabled.

    18

  • 8/4/2019 52631387 MC0070 Operating System

    19/25

    -f default_inactive: The number of days after a password has expired before the accountwill be disabled.

    -g default_group: The group name or ID for a new users initial group. The named groupmust exist, and a numerical group ID must have an existing entry.

    -s default_shell: The name of the new users login shell. The named program will be usedfor all future new user accounts.

    GROUPADD: Creates a new group account.

    SYNTAX

    groupadd [-g gid [-o]] group

    -g gid: The numerical value of the groups ID. This value must be unique, unless the -o

    option is used. The value must be non-negative. The default is to use the smallest ID valuegreater than 99 and greater than every other group. Values between 0 and 99 are typicallyreserved for system accounts

    USERDEL: Enables a super user to remove a users account.

    userdel [-r] login

    -r: Files in the users home directory will be removed along with the home directory itselfand the users mail spool.

    EXIT VALUES

    0 success 1 cant update password file2 bad command syntax 6 specified user doesnt exist8 user currently logged in 10 cant update group file12 cant remove home directory

    EXAMPLE: userdel -r newperson

    USERMOD: Enables a super user or root user to modify a users account.

    SYNTAX

    usermod [-c comment] [-d home_dir [ -m]] [-e expire_date] [-f inactive_time] [-ginitial_group] [-G group[,...]] [-l login_name] [-p passwd] [-s shell] [-u uid [ -o]] [-L|-U]login

    Same as user add command

    The /etc/passwd File

    UNIX uses the /etc/passwd file to keep track of every user on the system. The /etc/passwdfile contains the username, real name, identification information, and basic account

    19

  • 8/4/2019 52631387 MC0070 Operating System

    20/25

    information for each user. Each line in the file contains a database record; the record fieldsare separated by a colon (:).

    You can use the cat command to display your systems /etc/passwd file. Here are a fewsample lines from a typical file:

    root:fi3sED95ibqR6:0:1:System Operator:/:/bin/ksh

    daemon:*:1:1::/tmp:

    rachel:eH5/.mj7NB3dx:181:100:Rachel Cohen:/u/rachel:/bin/ksh

    The first two accounts, root and daemon are system accounts, while rachel is an accountsfor individual users.

    The individual fields of the /etc/passwd file are:

    Field Contents

    Rachel The username

    EH5/.mj7NB3dx the users "encrypted password"

    181 Users user identification number (UID)

    100 Users group identification number (GID)

    Rachel Cohen The users full name

    /u/rachel The users home directory

    /bin/ksh The users shell

    Passwords are normally represented by a special encrypted format and is not stored in thefile. Encrypted passwords may also be stored in separate shadow password files

    The Shadow File: The shadow file is not readable to every user and the permissions are set

    to be readable only by the root user. The shadow file has a similar format to the passwdfile.

    example:$1$7RhT4hhG$K3fEau5Tn..uEJUq8tjEn/:11109:0:

    99999:7:-1:-1:1075502268

    example The users login name.

    1$7RhT4hhG$K3fEau5Tn..uEJUq8tjEn/: Encrypted password.

    11109: The number of days (since January 1, 1970) since the password was last changed.

    20

  • 8/4/2019 52631387 MC0070 Operating System

    21/25

    0: The no. of days before password may be changed (0 indicates it may be changed at anytime).

    99999: The no. of days after which password must be changed

    7: The no. of days to warn user of an expiring password

    -1: The no. of days after password expires that account is disabled.

    Que 6. Explain the following with respect to Interprocesscommunication in Unix:A) Communication via pipesB) Named PipesC) Message Queues

    D) Message Structure

    Ans:-

    A)Communication via pipes

    Once we got our processes to run, we suddenly realize that they cannotcommunicate. One of the mechanisms that allow related-processes to communicateis the pipe, or the anonymous pipe. A pipe is a one-way mechanism that allows tworelated processes (i.e. one is an ancestor of the other) to send a byte stream from oneof them to the other one. If we want a two-way communication, well need two

    pipes. The system assures us of one thing: The order in which data is written to thepipe, is the same order as that in which data is read from the pipe. The system alsoassures that data wont get lost in the middle, unless one of the processes (the senderor the receiver) exits prematurely.

    B) Named Pipes

    Named Pipe

    A named pipe (also called a named FIFO, or just FIFO) is a pipe whose access point is afile kept on the file system.

    By opening this file for reading, a process gets access to the reading end of the pipe.

    By opening the file for writing, the process gets access to the writing end of the pipe.

    If a process opens the file for reading, it is blocked until another process opens the file forwriting. The same goes the other way around.

    Creating a Named Pipe

    21

  • 8/4/2019 52631387 MC0070 Operating System

    22/25

    A named pipe may be created either via the mknod (or its newer replacement, mkfifo),or via the mknod() system call

    To create a named pipe with the file named prog_pipe, we can use the followingcommand:

    mknod prog_pipe p

    We could also provide a full path to where we want the named pipe created. If we then typels -l prog_pipe, we will see something like this:

    prw-rw-r 1 user1 0 Nov 7 01:59 prog_pipe

    The p on the first column denotes this is a named pipe. Just like any file in the system, ithas access permissions, that define which users may open the named pipe, and whether forreading, writing or both.

    C) Message Queues

    A message queue is a queue onto which messages can be placed. A message is composed ofa message type (which is a number), and message data.

    A message queue can be either private, or public. If it is private, it can be accessedonly by its creating process or child processes of that creator. If its public, it can be

    accessed by any process that knows the queues key.

    Several processes may write messages onto a message queue, or read messages from thequeue. Messages may be read by type, and thus not have to be read in a FIFO order as is thecase with pipes.

    Creating A Message Queue msgget()

    In order to use a message queue, it has to be created first. The msgget() system call is usedto do just that. This system call accepts two parameters a queue key, and flags. The keymay be one of:

    IPC_PRIVATE used to create a private message queue.

    a positive integer used to create (or access) a publicly-accessible message queue.

    The second parameter contains flags that control how the system call is to be processed. Itmay contain flags like IPC_CREAT or IPC_EXCL and it also contains access permission

    bits.

    22

  • 8/4/2019 52631387 MC0070 Operating System

    23/25

    D) Message Structure

    Message Structure struct msgbuf

    Before we go to writing messages to the queue or reading messages from it, we need to seehow a message looks. The system defines a structure named msgbuf for this purpose.Here is how it is defined:

    struct msgbuf {

    long mtype; /* message type, a positive number (cannot be

    zero). */

    char mtext[1]; /* message body array. usually larger than

    one byte. */

    };Lets create an "hello world" message:

    /* first, define the message string */

    char* msg_text = "hello world";

    /* allocate a message with enough space for length of string and */ /* one extra byte for theterminating null character. */

    struct msgbuf* msg = (struct msgbuf*)malloc(sizeof(struct msgbuf) + strlen(msg_text));

    /* set the message type. for example set it to 1. */

    msg->mtype = 1; /* finally, place the "hello world" string inside the message. */

    strcpy(msg->mtext, msg_text);

    3.6.5.1 Writing Messages Onto A Queue msgsnd()

    Once we created the message queue, and a message structure, we can place it on themessage queue, using the msgsnd() system call. This system call copies our messagestructure and places that as the last message on the queue. It takes the following parameters:

    int msqid id of message queue, as returned from the msgget() call.

    23

  • 8/4/2019 52631387 MC0070 Operating System

    24/25

    struct msgbuf* msg a pointer to a properly initializes message structure, such as the onewe prepared in the previous section.

    int msgsz the size of the data part (mtext) of the message, in bytes.

    int msgflg flags specifying how to send the message. may be a logical "or" of thefollowing:

    IPC_NOWAIT if the message cannot be sent immediately, without blocking the process,return -1, and set errno to EAGAIN.

    to set no flags, use the value 0.

    in order to send our message on the queue, well use msgsnd() like this:

    int rc = msgsnd(queue_id, msg, strlen(msg_text)+1, 0);

    if (rc == -1) {

    perror("msgsnd");

    exit(1);

    }

    3.6.5.2 Reading A Message From The Queue msgrcv()

    We may use the system call msgrcv() In order to read a message from a message queue.This system call accepts the following list of parameters:

    int msqid id of the queue, as returned from msgget().

    struct msgbuf* msg a pointer to a pre-allocated msgbuf structure. It should generally belarge enough to contain a message with some arbitrary data (see more below).

    int msgsz size of largest message text we wish to receive. Must NOT be larger than theamount of space we allocated for the message text in msg.

    int msgtyp Type of message we wish to read. may be one of:

    0 The first message on the queue will be returned.

    a positive integer the first message on the queue whose type (mtype) equals this integer(unless a certain flag is set in msgflg, see below).

    a negative integer the first message on the queue whose type is less than or equal to theabsolute value of this integer.

    int msgflg a logical or combination of any of the following flags:

    24

  • 8/4/2019 52631387 MC0070 Operating System

    25/25

    IPC_NOWAIT if there is no message on the queue matching what we want to read, return-1, and set errno to ENOMSG.

    MSG_EXCEPT if the message type parameter is a positive integer, then return the firstmessage whose type is NOT equal to the given integer.

    Lets then try to read our message from the message queue:

    /* message structure large enough to read our "hello world". */

    struct msgbuf* recv_msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("helloworld")); /*

    use msgrcv() to read the message. We agree to get any type, and thus */ /* use 0 in themessage type parameter, and use no flags (0). */

    int rc = msgrcv(queue_id, recv_msg, strlen("hello world")+1, 0, 0);

    if (rc == -1) { perror("msgrcv"); exit(1); }

    25