mc0070_august_2010_operating systems with unix

Upload: harvinder-singh

Post on 08-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    1/27

    August 2010Master of Computer Application (MCA) Semester 2

    MC0070 Operating Systems with Unix 4 Credits

    (Book ID: B0682 & B0683) Assignment Set 1

    1. Describe the following operating system components:

    A) Functions of an Operating system

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

    To hide details of hardware: An abstraction is software that hides lower level details andprovides a set of higher-level functions. An operating system transforms the physical world of devices, instructions, memory, and time into virtual world that is the result of abstractions builtby the operating system. 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 for example, input/output operations.

    Second , the operating system introduces new functions as it abstracts the hardware. For instance, operating system introduces the file abstraction so that programs do not have todeal 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 aprocess. Each process views the hardware through the lens of abstraction.

    Fourth , the operating system can enforce security through abstraction.

    Resources Management: An operating system as resource manager, controls howprocesses (the active agents) may access resources (passive entities). One can viewOperating Systems from two points of views: Resource manager and Extended machines.

    Form Resource manager point of view Operating Systems manage the different parts of thesystem efficiently and from extended machines point of view Operating Systems provide avirtual machine to users that is more convenient to use. The structurally Operating Systemscan be design as a monolithic system, a hierarchy of layers, a virtual machine system, amicro-kernel, or using the client-server model. The basic concepts of Operating Systems areprocesses, memory management, I/O management, the file systems, and security.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    2/27

    Provide a effective user interface: The user interacts with the operating systems throughthe user interface and usually interested in the look and feel of the operating system. Themost important components of the user interface are the command interpreter, the filesystem, on-line help, and application integration. The recent trend has been toward

    increasingly integrated graphical user interfaces that encompass the activities of multipleprocesses on networks of computers.

    B) Operating system components

    Ans: Even though, not all systems have the same structure many modern operating systems sharethe same goal of supporting the following types of system components.

    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 activities isencapsulated in a process. A process includes the complete execution context (code, data,PC, registers, OS resources in use etc.).

    It is important to note that a process is not a program. A process is only ONE instant of aprogram in execution. There are many processes can be running the same program. The fivemajor activities of an operating 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.

    Main-Memory Management: Primary-Memory or Main-Memory is a large array of words or bytes. Each word or byte has its own address. Main-memory provides storage that can beaccess directly by the CPU. That is to say for a program to be executed, it must in the mainmemory.

    The major activities of an operating in regard to memory-management are:

    1. Keep track of which part of memory are currently being used and by whom.

    2. Decide which processes are loaded into memory when memory space becomes available.

    3. Allocate and de-allocate memory space as needed.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    3/27

    File Management: A file is a collection of related information defined by its creator. Computer can store 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 directories maycontain files and other directions.

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

    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.

    I/O System Management: I/O subsystem hides the peculiarities of specific hardware devicesfrom the user. Only the device driver knows the peculiarities of the specific device to whom itis assigned.

    Secondary-Storage Management: Generally speaking, systems have several levels of storage, including primary storage, secondary storage and cache storage. Instructions anddata must be placed in primary storage or cache to be referenced by a running program.Because main memory is too small to accommodate all data and programs, and its data arelost when power is lost, the computer system must provide secondary storage to back upmain memory. Secondary storage consists of tapes, disks, and other media designed to holdinformation that will eventually be accessed in primary storage (primary, secondary, cache) isordinarily divided into bytes or words consisting of a fixed number of bytes. Each location instorage has an address; the set of all addresses available to a program is called an addressspace.

    The three major activities of an operating system in regard to secondary storage managementare:

    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.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    4/27

    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.

    Protection System: If a computer system has multiple users and allows the concurrentexecution of multiple processes, then various processes must be protected from oneanothers activities. Protection refers to mechanism for controlling the access of programs,processes, or users to the resources defined by a computer system.

    Command Interpreter System: A command interpreter is an interface of the operatingsystem with the user. The user gives commands with are executed by operating system(usually by turning them into system calls). The main function of a command interpreter is toget and execute the next user specified command. Command-Interpreter is usually not part of

    the kernel, since multiple command interpreters (shell, in UNIX terminology) may besupported by an operating system, and they do not really need to run in kernel mode. Thereare two main advantages of 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 isseparate from the kernel. I cannot change the code of the kernel so I cannot modify theinterface.

    2. If the command interpreter is a part of the kernel, it is possible for a malicious process to

    gain 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.

    2. Describe the following:

    A) Micro Kernels

    Ans: Micro-kernels: We have already seen that as UNIX expanded, the kernel became large anddifficult to manage. 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 smaller

    kernel. There is little consensus regarding which services should remain in the kernel andwhich should be implemented in user space. Typically, however, micro-kernels provideminimal process and memory management, in addition to a communication facility.

    DeviceDrivers

    File Server ClientProcess . VirtualMemory

    Microkernel

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    5/27

    Hardware

    Microkernel Architecture

    The main function of the microkernel is to provide a communication facility between the client

    program and the various services that are also running in user space. Communication isprovided by message passing. For example, if the client program and service never interactdirectly. Rather, they communicate indirectly by exchanging messages with the microkernel.

    On benefit of the microkernel approach is ease of extending the operating system. All newservices 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 themicrokernel is a smaller kernel. The resulting operating system is easier to port from onehardware design to another. The microkernel also provided more security and reliability, sincemost services are running as user rather than kernel processes, if a service 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 is implemented with aMarch kernel. The March kernel maps UNIX system calls into messages to the appropriateuser-level services.

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

    UNIX Architecture

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    6/27

    B) Modules

    Ans: Modules: Perhaps the best current methodology for operating-system design involves usingobject-oriented programming techniques to create a modular kernel. Here, the kernel has aset of core components and dynamically links in additional services either during boot time or during 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 of loadable kernel modules:

    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 loadable modules.The overall result resembles a layered system in that each kernel section has defined,protected interfaces; but it is more flexible than a layered system in that any module can callany other module. Furthermore, the approach is like the microkernel approach in that theprimary module has only core functions and knowledge of how to load and communicate withother modules; but it is more efficient, because modules do not need to invoke messagepassing in order to communicate.

    3. Describe the concept of process control in Operating systems.

    Ans: The structure of a process, process control block, modes of process execution, and processswitching.

    Process Structure: After studying the process states now we will see where does theprocess reside, and what is 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 thisprocess, at least small part of this process is maintained in the main memory. To execute theprocess, 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 identificationProcessor state informationProcess control informationUser StackPrivate user address space (program, data)Shared address space

    Process Image

    The obvious contents of a process are User Program to be executed, and the User Data which is associated with that program. Apart from these there are two major parts of aprocess; System Stack , which is used to store parameters and calling addresses for

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    7/27

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    8/27

    Modes of Execution: In order to ensure the correct execution of each process, an operatingsystem must protect each processs private information (executable code, data, and stack)from uncontrolled interferences from other processes. This is accomplished by suitablyrestricting the memory address space available to a process for reading/writing, so that the

    OS can regain CPU control through hardware-generated exceptions whenever a processviolates those restrictions.

    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 readingor altering a control register such as program status word, primitive I/O instruction; andmemory management instructions.

    The less privileged mode is referred as user mode as typically user programs are executed inthis mode, and the more privileged mode in which important operating system functions areexecuted 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 privilegedmode. 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 theCPU, a hardware clock generates interrupts periodically. This allows the operating system toschedule all processes in main memory (using scheduling algorithm) to run on the CPU atequal intervals. Each time a clock interrupt occurs, the interrupt handler checks how muchtime the current running process has used. If it has used up its entire time slice, then the CPUscheduling algorithm (in kernel) picks a different process to run. Each switch of the CPU fromone 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 processP0 to process P1.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    9/27

    Process switching

    A context switch is sometimes described as the kernel suspending execution of one processon the CPU and resuming execution of some other process that had previously beensuspended.

    A context switch occurs due to interrupts, trap (error due to the current instruction) or asystem call as described bellow:

    Clock interrupt: when a process has executed its current time quantum which was allocatedto it, the process must be switched from running state to ready state, and another processmust be dispatched for execution.

    I/O interrupt: whenever any I/O related event occurs, the OS is interrupted, the OS has todetermine the reason of it and take necessary action for that event. Thus the current processis switched to ready state and the interrupt routine is loaded to do the action for the interruptevent (e.g. after an I/O interrupt the OS moves all the processes which were blocked on theevent, from blocked state to ready state, and blocked/suspended to ready/suspended state).

    After completion of the interrupt related actions, it is expected that the process which wasswitched, should be brought for execution, but that does not happen. At this point thescheduler again decides which process is to be scheduled for execution from all the readyprocesses afresh. This is important as it will schedule any high priority process present in theready queue added during the interrupt handling period.

    Memory fault: when virtual memory technique is used for memory management, many atimes it happens that a process refers to a memory address which is not present in the main

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    10/27

    memory, and needs to be brought in. As the memory block transfer takes time, another process should be given chance for execution and the current process should be blocked.Thus the OS blocks the current process, issues an I/O request to get the memory block in thememory and switches the current process to blocked state, and loads another process for

    execution.

    Trap: if the instruction being executed has any error or exception, depending on thecriticalness of the error / exception and design of operating system, it may either move theprocess to exit state, or may execute the current process after a possible recovery.

    System call: many a times a process has to invoke a system call for a privileged job, for thisthe current process is blocked and the respective operating systems system call code isexecuted. Thus the context of the current process is switched to the system call code.

    4. Describe the following with respect to UNIX operating System:

    A) Hardware Management

    Ans: 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 startingfunctions 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 aprocedure that makes sure all the hardware is shut down correctly. Before turning your computer 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.

    Process Management: After the operating system completes hardware initialization, you canexecute an application. This executing application is called a process. It is the operatingsystems job to manage execution of the application. When you execute a program, theoperating system creates a new process. Many processes can exist simultaneously, but onlyone process can actually be executing on a CPU at one time. The operating system switchesbetween your processes so quickly that it can appear that the processes are executingsimultaneously. This concept is referred to as time-sharing or multitasking.

    When you exit your program (or it finishes executing), the process terminates, and theoperating system manages the termination by reclaiming any resources that were being used.

    Most applications perform some tasks between the time that the process is created and thetime that it terminates. To perform these tasks, the program makes requests to the operatingsystem and the operating system responds to the requests and allocates necessaryresources to the program. When an executing process needs to use some hardware, theoperating system provides access for the process.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    11/27

    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 another computer), or send data to a printer. The operating system provides such services for theprocess. This is referred to as resource allocation. A piece of hardware is a resource, and the

    operating 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) does tomanage them.

    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 processruns

    Process 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 iscoordinating the operations. As hardware is initialized, accessed, or shut down, the operatingsystem manages these resources. As applications execute, request, and receive resources,or terminate, the operating system takes care of these actions. Without an operating system,no application can run and your computer is just an expensive paperweight.

    B) Unix Architecture

    Ans: UNIX, like other operating systems, is a layer between the hardware and the applications thatrun on the computer. It has functions that manage the hardware and functions that manageexecuting applications. So whats the difference between UNIX and any other operatingsystem? Basically two things: internal implementation and the interface that is seen and usedby users. For the most part this book ignores the internal implementation. If you wish to knowthese details, many texts exist that cover them. The interface is what this book describes indetail. The majority of UNIX users need to be familiar with the interface and need notunderstand the internal workings of UNIX.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    12/27

    UNIX is a very powerful and fast operating system and is the only serious competitor to theMicrosoft world left in the operating system market. It is also very old: UNIX dates back intothe 1970s. What could be considered a weakness is actually strength: UNIX has been flexibleenough to accommodate 30 years worth of hardware and software development and is very

    likely to continue to do so. The faint hearted are put of by UNIX because of its sometimescryptic command language and its complexity. However with an inquisitive mind andplayfulness the power of UNIX can be easily mastered. Eventually you may realize thatcryptic commands actually save time because you do not need to type so much. Unix IS user friendly, it may just be a bit particular about who its friends are! The complexity arises fromthe fact that a modern operating system provides so many services to its users. In contrast toWindows, the configuration of such services is always accessible under UNIX.

    UNIX Architecture

    At the center of the UNIX onion is a program called the kernel. It is absolutely crucial to theoperation of the UNIX system. The kernel provides the essential services that make up theheart of UNIX systems; it allocates memory, keeps track of the physical location of files on thecomputers hard disks, loads and executes binary programs such as shells, and schedulesthe task swapping without which UNIX systems would be incapable of doing more than onething at a time.

    The kernel accomplishes all these tasks by providing an interface between the other programs running under its control and the physical hardware of the computer; this interface,

    the system call interface, effectively insulates the other programs on the UNIX system fromthe complexities of the computer. For example, when a running program needs access to afile, it cannot simply open the file; instead it issues a system call which asks the kernel toopen the file. The kernel takes over and handles the request, then notifies the programwhether the request succeeded or failed. To read data in from the file takes another systemcall; the kernel determines whether or not the request is valid, and if it is, the kernel reads therequired block of data and passes it back to the program. Unlike DOS (and some other

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    13/27

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

    Although there is a well-defined, technical and commercial standard for what constitutesUnix, 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 affect howcommands are interpreted. Your default is that you are using Solaris (developed by SunMicrosystems primarily for use on hardware sold by Sun) within the c-shell. Most of thebasic commands here will work the same in other Unix variants and shells, including Linuxand the Mac OS X command-line environment.

    All Unix commands and file references are case sensitive: This is a different filename thanthis because of the capitalization difference. All Unix commands are lowercase and from twoto nine characters long. Many commands have options that are invoked by a hyphen followedby one or more letters. Multiple options can often be requested by adding multiple letters to asingle hyphen. For example, ls -al combines the -a and -l options.

    A standard Unix system provides commands username, passwd, chsh, and additionaloptions on chdgrp to change usernames, passwords, default groups, and shellenvironments.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    14/27

    Wildcards: * is a wildcard character that can refer to any character string and ? is a wildcardcharacter 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, or nonprinting 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. A pathnamenot 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.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    15/27

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    16/27

    5. Describe the following:

    A) Unix Kernel

    Ans: Most Unix systems implement a two-stage loading process: During the first stage, a smallboot 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 vendor-dependent. For example, it is /vmunix on SunOS 4.x, Digital Unix and Ultrix, /kernel/unix onSunOS 5.x, or /unix on IRIX and AIX systems. Once the kernel is loaded, it remains in thememory during the running of the system.

    The kernel probes the bus to locate the devices specified during the configuration, andinitializes the located devices (ignoring those that it cant contact). Any device not detectedand initialized during the boot will not be accessible to system until it is properly connectedand the system is rebooted.

    System Processes: The kernel identifies the root, swap, and dump devices and then startsprograms to schedule processes, manage physical memory and virtual memory, and the initprocess. BSD systems starts three initialization processes; swapper, init and pagedaemon.On the SVR4 systems the initialization processes include sched, init, and various memoryhandlers (except on Solaris).

    sched: The real-time scheduler, sched, runs as process 0 on SVR5 systems. It can be usedto set 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 physical

    memory 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 process runsas process 1 and always remains in the background when the system is running. If the

    system 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.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    17/27

    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 command fsck,usually found in the /etc directory.

    B) Unix Startup Scripts

    Ans: The startup scripts are merely shell scripts, so init spawns a copy of sh to interpret them. Thestartup scripts are defined and organized differently on different systems. On BSD systemsthe startup scripts may be found in the /etc directory and their names begin with rc, e.g.,/etc/rc.boot, /etc/rc.single, /etc/rc.local and so on. SVR5 systems define various run levels inwhich 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 to take. The syntax of inittabentries 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.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    18/27

    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.

    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 username defined to thesystem. This login name identifies the user. When a newuser is added to unix systemssystems administrator assigns it a unique login name which is associated with a number

    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 of users in onedepartment or working on one project identified with one group name. Each group is identifiedwith 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 files anddirectories.

    Procedures to add a new user to system:

    Get users name and create a login id based on name, decide which group and which other groups 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.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    19/27

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

    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 user information.

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

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

    [-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 inthe format YYYY-MM-DD.

    -f inactive_time: The number of days after a password expires until the account ispermanently 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 group namemust exist. The default group no. is 1.

    -G group,[,...]: A list of supplementary groups which the user is also a member of. Each groupis separated from the next by a comma, with no intervening whitespace.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    20/27

    -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 -o optionis used. The value must be non-negative. The default is to use the smallest ID value greater than 99 and greater than every other user. Values between 0 and 99 are typically reserved for system accounts.

    -b default_home: The initial path prefix for a new users home directory. The users name willbe affixed to the end of default_home to create the new directory name if the -d option is notused when creating a new account.

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

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

    -g default_group: The group name or ID for a new users initial group. The named group must

    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 used for 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 optionis used. The value must be non-negative. The default is to use the smallest ID value greater than 99 and greater than every other group. Values between 0 and 99 are typically reservedfor system accounts

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

    userdel [-r] login

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    21/27

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

    EXIT VALUES

    0 success 1 cant update password file

    2 bad command syntax 6 specified user doesnt exist

    8 user currently logged in 10 cant update group file

    12 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] [-g initial_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/passwd filecontains the username, real name, identification information, and basic account informationfor each user. Each line in the file contains a database record; the record fields are separatedby 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 accounts for individual users.

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

    Field Contents

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    22/27

    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 setto be readable only by the root user. The shadow file has a similar format to the passwd file.

    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.

    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.

    -1: The number of days since January 1, 1970 that an account has been disabled

    1075502268: Not presently used.

    The shadow password file is kept in different places for different types of Unixes. Theexample given (/etc/shadow) is for a Redhat based linux system. The format of the shadowfile also varies from system to system.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    23/27

    6. Explain the following with respect to Interprocess communication in Unix:

    A) Communication via pipes

    Ans: Once we got our processes to run, we suddenly realize that they cannot communicate. One of the mechanisms that allow related-processes to communicate is the pipe, or the anonymous

    pipe.

    A pipe is a one-way mechanism that allows two related processes (i.e. one is an ancestor of the other) to send a byte stream from one of them to the other one.

    If we want a two-way communication, well need two pipes. The system assures us of onething: The order in which data is written to the pipe, is the same order as that in which data isread from the pipe. The system also assures that data wont get lost in the middle, unless oneof the processes (the sender or the receiver) exits prematurely.

    The pipe() System Call: This system call is used to create a read-write pipe that may later beused to communicate with a process well fork off. The call takes as an argument an array of 2 integers that will be used to save the two file descriptors used to access the pipe. The firstto read from the pipe, and the second to write to the pipe. Here is how to use this function:

    /* first, define an array to store the two file descriptors */

    int pipes[2]; /* now, create the pipe */

    int rc = pipe(pipes);

    if (rc == -1){ /* pipe() failed */

    perror("pipe");

    exit(1);

    }

    #include

    #include /* defines pipe(), amongst other things. *//* this routine handles the work of the child process. */

    void do_child(int data_pipe[])

    { int c; /* data received from the parent. */

    int rc; /* return status of read(). */

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    24/27

    close(data_pipe[1]); // close the un-needed write-part of the pipe.

    /* now enter a loop of reading data from the pipe, and printing it */

    while ((rc = read(data_pipe[0], &c, 1)) > 0)

    {

    putchar(c); }

    exit(0); //may be pipe was broken, or got EOF via the pipe.

    }

    /* this routine handles the work of the parent process. */

    void do_parent(int data_pipe[])

    { int c; /* data received from the user. */

    int rc; /* return status of getchar(). */

    close(data_pipe[0]); //close the un-needed read-part of pipe.

    //enter a loop of read user input, and writing it to the pipe.

    while ((c = getchar()) > 0)

    { rc = write(data_pipe[1], &c, 1); //write character to the pipe.

    if (rc == -1) // write failed notify the user and exit

    {

    perror("Parent: write");

    close(data_pipe[1]);

    exit(1); }

    }

    close(data_pipe[1]); /* probably got EOF from the user.

    /* close the pipe, to let the child know were done. */

    exit(0); }

    int main(int argc, char* argv[])

    { int data_pipe[2]; //array to store the file descriptors of pipe.

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    25/27

    int pid; // pid of child process, or 0, as returned via fork.

    int rc; // stores return values of various routines.

    rc = pipe(data_pipe); // first, create a pipe.

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

    pid = fork();

    switch (pid) { case -1: perror("fork"); exit(1);

    case 0: do_child(data_pipe);

    default: do_parent(data_pipe);

    }

    return 0; }

    B) Named Pipes

    Ans: A named pipe (also called a named FIFO, or just FIFO) is a pipe whose access point is a filekept 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 for writing. The same goes the other way around.

    Creating A Named Pipe: 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 following command:

    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, it hasaccess permissions, that define which users may open the named pipe, and whether for reading, writing or both.

    C) Message Queues

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    26/27

    Ans: A message queue is a queue onto which messages can be placed. A message is composedof a 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 accessed only by itscreating process or child processes of that creator. If its public, it can be accessed by anyprocess 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 isthe case with pipes.

    Creating A Message Queue msgget(): In order to use a message queue, it has to becreated first. The msgget() system call is used to do just that. This system call accepts twoparameters a queue key, and flags. The key may 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.

    Example of a code that creates a private message queue:

    #include /* standard I/O routines. */

    #include /* standard system data types.

    #include /* common system V IPC structures. */

    #include /* message-queue specific functions. */

    int queue_id = msgget(IPC_PRIVATE, 0600); // octal number.

    if (queue_id == -1) { perror("msgget"); exit(1); }

    1. The system call returns an integer identifying the created queue. Later on we can use thiskey in order to access the queue for reading and writing messages.

    2. The queue created belongs to the user whose process created the queue. Thus, since thepermission bits are 0600 , only processes run on behalf of this user will have access to thequeue.

    D) Message Structure

  • 8/7/2019 MC0070_August_2010_Operating Systems with Unix

    27/27

    Ans: 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. Hereis 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 forthe terminating 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);