53252878 mc0070 august 2010 operating systems with unix

Upload: nabarupam-deb

Post on 06-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    1/28

    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 Operatingsystem

    Ans: Modern Operating systems generally have following three major goals. Operating systems generally accomplish these goals by running processes in low privilege and providing service calls that invoke the operating system kernel in high-privilege state. To hide details of hardware: An abstraction is software that hides lower level details and provides 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 built by the operating system. There are several reasons for abstraction. First, the code needed to cont

    rol peripheral devices is not standardized. Operating systems provide 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 to deal with disks. Third, the operating system transforms the computer hardware into multiple virtual computers, 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. Resources Management: An operating system as resource manager, controls how processes (the activeagents) may access resources (passive entities). One can view Operating Systemsfrom two points of views: Resource manager and Extended machines. Form Resourcemanager point of view Operating Systems manage the different parts of the syste

    m efficiently and from extended machines point of view Operating Systems providea virtual machine to users that is more convenient to use. The structurally Operating Systems can be design as a monolithic system, a hierarchy of layers, a virtual machine system, a micro-kernel, or using the client-server model. The basic concepts of Operating Systems are processes, memory management, I/O management, the file systems, and security.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    2/28

    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 theoperating system. The most important components of the user interface are the command interpreter, the file system, on-line help, and application integration. The recent trend has been toward increasingly integrated graphical user interface

    s that encompass the activities of multiple processes on networks of computers.B) Operating system components

    Ans: Even though, not all systems have the same structure many modern operatingsystems share the same goal of supporting the following types of system components. Process Management The operating system manages many kinds of activities ranging from user programs to system programs like printer spooler, name servers, file server etc. Each of these activities is encapsulated in a process. A processincludes 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 a program in execution. There are many processes can be running the same program. The five major 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 largearray of words or bytes. Each word or byte has its own address. Main-memory provides storage that can be access directly by the CPU. That is to say for a program to be executed, it must in the main memory. The major activities of an operating in regard to memory-management are: 1. Keep track of which part of memory arecurrently 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/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    3/28

    File Management: A file is a collection of related information defined by its creator. Computer can store files on the disk (secondary storage), which provideslong term storage. Some examples of storage media are magnetic tape, magnetic disk and optical disk. Each of these media has its own properties like speed, capacity, data transfer rate and access methods. A file system normally organized in

    to directories to ease their use. These directories may contain files and otherdirections. 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 devices from the user. Only the device driver knowsthe peculiarities of the specific device to whom it is assigned. Secondary-Storage Management: Generally speaking, systems have several levels of storage, including primary storage, 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 is too small to accommodate all data and programs, and i

    ts data are lost when power is lost, the computer system must provide secondarystorage to back up main memory. Secondary storage consists of tapes, disks, andother media designed to hold information that will eventually be accessed in primary storage (primary, secondary, cache) is ordinarily divided into bytes or words consisting of a fixed number of bytes. Each location in storage has an address; 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.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    4/28

    Networking: A distributed system is a collection of processors that do not sharememory, peripheral devices, or a clock. The processors communicate with one another through communication 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 a

    llows 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 users to the resources definedby a computer system. Command Interpreter System: A command interpreter is an interface of the operating system with the user. The user gives commands with areexecuted by operating system (usually by turning them into system calls). The main function of a command interpreter is to get 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 be supported by an operating system, and they do not really need to run in kernel mode. There are 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 the i

    nterface of command interpreter, I am able to do that if the command interpreteris separate from the kernel. I cannot change the code of the kernel so I cannotmodify the interface. 2. If the command interpreter is a part of the kernel, itis possible for a malicious process to gain access to certain part of the kernel that it should not have. To avoid this scenario it is advantageous to have thecommand 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 and difficult to manage. In the mid-1980s, researches at Carnegie MellonUniversity developed an operating system called Mach that modularized the kernel using the microkernel approach. This method structures the operating system byremoving all nonessential components from the kernel and implementing then as s

    ystem and user-level programs. The result is a smaller kernel. There is little consensus regarding which services should remain in the kernel and which should be implemented in user space. Typically, however, micro-kernels provide minimal process and memory management, in addition to a communication facility. Device Drivers Microkernel Client Process Virtual Memory

    File Server

    .

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    5/28

    HardwareMicrokernel 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 sp

    ace. Communication is provided by message passing. For example, if the client program and service never interact directly. Rather, they communicate indirectly by exchanging messages with the microkernel. On benefit of the microkernel approach is ease of extending the operating system. All new services are added to userspace 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 port from one hardware design to another. The microkernel also provided more security and reliability, since most services are running as user rather than kernel processes,if a service fails the rest of the operating system remains untouched. Severalcontemporary operating systems have used the microkernel approach. Tru64 UNIX (formerly Digital UNIX provides a UNIX interface to the user, but it is implemente

    d with a March kernel. The March kernel maps UNIX system calls into messages tothe appropriate user-level services. The following figure shows the UNIX operating system architecture. At the center is hardware, covered by kernel. Above thatare the UNIX utilities, and command interface, such as shell (sh), etc.

    UNIX Architecture

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    6/28

    B)

    Modules

    Ans: Modules: Perhaps the best current methodology for operating-system design i

    nvolves using object-oriented programming techniques to create a modular kernel.Here, the kernel has a set 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 in modern implementations of UNIX, suchas Solaris, Linux and MacOSX. For example, the Solaris 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 certainfeatures to be implemented dynamically. For example device and bus drivers forspecific hardware can be added 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 call any other module.

    Furthermore, the approach is like the microkernel approach in that the primary 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 message passing 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 process switching. Process Structure: After studying the process statesnow we will see where does the process reside, and what is the physical manifestation of a process? The location of the process depends on memory management scheme being used. In the simplest 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 execute the process, the entire process or part of i

    t is brought in the main memory, and for that the operating system need to knowthe location of the process.Process identification Processor state information Process control information User Stack Private user address space (program, data) Shared address spaceProcess Image

    The obvious contents of a process are User Program to be executed, and the UserData which is associated with that program. Apart from these there are two majorparts of a process; System Stack, which is used to store parameters and callingaddresses for

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    7/28

    procedure and system calls, and Process Control Block, this is nothing but collection of process attributes needed by operating system to control a process. Thecollection of user program, data, system stack, and process control block is called as Process Image as shown in the above figure. Process Control Block: A process control block as shown in the figure 3.4 bellow, contains various attribute

    s required by operating system to control a process, such as process state, program counter, CPU state, CPU scheduling information, memory management information, I/O state information, 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 of the 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 whos this processis being run. The Processor state information consists of the contents of the processor registers, such as user-visible registers, control and status registerswhich includes program counter and program status word, and stack pointers. Thethird category Process Control Identification is mainly required for the control

    of a process. The information includes: scheduling and state information, datastructuring, interprocess communication, process privileges memory management, and resource ownership and utilization. pointer process number program counter registers memory limits list of open files . . . Process Control Block process state

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    8/28

    Modes of Execution: In order to ensure the correct execution of each process, anoperating system must protect each processs private information (executable code, data, and stack) from uncontrolled interferences from other processes. This isaccomplished by suitably restricting the memory address space available to a process for reading/writing, so that the OS can regain CPU control through hardwar

    e-generated exceptions whenever a process violates those restrictions. Also theOS code needs to execute in a privileged condition with respect to normal: to manage processes, it needs to be enabled to execute operations which are forbidden to normal 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 executed in thismode, and the more privileged mode in which important operating system functions are 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 in user mode or kernel mode. The mode change is normally done by executing change

    mode instruction; typically after a user process invokes a system call, or whenever an interrupt occurs, as these are operating system functions and needed tobe executed in privileged mode. After the completion of system call or interruptroutine, the mode is again changed to user mode to continue the user process execution. Context Switching: To give each process on a multiprogrammed machine afair share of the CPU, a hardware clock generates interrupts periodically. Thisallows 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 time the current running process has used. If it has used up its entire time slice, then the CPU scheduling algorithm (in kernel) picks a different process to run. Each switch of the CPU from 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 ca

    n be described as the kernel (i.e., the core of the operating system) performingthe following activities with regard to processes on the CPU: (1) suspending the progression of one process and storing the CPUs state (i.e., the context) for that process somewhere in memory, (2) retrieving the context of the next processfrom memory and restoring it in the CPUs registers and (3) returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process. The figure 3.5 bellow depicts the process of context switch from process P0 to process P1.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    9/28

    Process switching A context switch is sometimes described as the kernel suspending execution of one process on the CPU and resuming execution of some other process that had previously been suspended. A context switch occurs due to interrupts, trap (error due to the current instruction) or a system call as described bellow: Clock interrupt: when a process has executed its current time quantum which

    was allocated to it, the process must be switched from running state to ready state, and another process must be dispatched for execution. I/O interrupt: whenever any I/O related event occurs, the OS is interrupted, the OS has to determinethe reason of it and take necessary action for that event. Thus the current process is switched to ready state and the interrupt routine is loaded to do the action for the interrupt event (e.g. after an I/O interrupt the OS moves all the processes which were blocked on the event, from blocked state to ready state, andblocked/suspended to ready/suspended state). After completion of the interruptrelated actions, it is expected that the process which was switched, should be brought for execution, but that does not happen. At this point the scheduler again decides which process is to be scheduled for execution from all the ready processes afresh. This is important as it will schedule any high priority process pr

    esent in the ready queue added during the interrupt handling period. Memory fault: when virtual memory technique is used for memory management, many a times ithappens that a process refers to a memory address which is not present in the main

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    10/28

    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 shouldbe blocked. Thus the OS blocks the current process, issues an I/O request to get the memory block in the memory and switches the current process to blocked state, and loads another process for execution. Trap: if the instruction being exec

    uted has any error or exception, depending on the criticalness of the error / exception and design of operating system, it may either move the process 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 this the current process is blocked and the respective operating systems system call code is executed. 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 and components, 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 hardware need to be initialized. After the start-up procedure is complete, the operating system awaits further instructions. Ifyou shut down the computer, the operating system also has a procedure that makes sure all the hardware is shut down correctly. Before turning your computer offagain, you might want to do something useful, which means that one or more applications 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 can executean application. This executing application is called a process. It is the operating systems job to manage execution of the application. When you execute a program, the operating system creates a new process. Many processes can exist simultaneously, but only one process can actually be executing on a CPU at one time. Theoperating system switches between your processes so quickly that it can appear

    that the processes are executing simultaneously. This concept is referred to astime-sharing or multitasking. When you exit your program (or it finishes executing), the process terminates, and the operating system manages the termination byreclaiming any resources that were being used. Most applications perform some tasks between the time that the process is created and the time that it terminates. To perform these tasks, the program makes requests to the operating system and the operating system responds to the requests and allocates necessary resources to the program. When an executing process needs to use some hardware, the operating system provides access for the process.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    11/28

    To perform its task, a process may need to access hardware resources. The process may need 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 the process. This is referred to as resource allocation. Apiece of hardware is a resource, and the operating system allocates available r

    esources to the different processes that are running. See Table 1.1 for a summary of different actions and what the operating system (OS) does to manage them. Operating system functions ACTION You turn on the computer You execute an application Application reads a tape Application waits for data Process waits while other process runs Process displays data on screen Process writes data to tape Youquit, the process terminates You turn off the computer OS DOES THIS Hardware management Process management Hardware management Process management Process management Hardware management Hardware management Process management 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 shu

    t down, the operating system manages these resources. As applications execute, request, and receive resources, or terminate, the operating system takes care ofthese 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 theapplications that run on the computer. It has functions that manage the hardware and functions that manage executing applications. So whats the difference between UNIX and any other operating system? Basically two things: internal implementation and the interface that is seen and used by users. For the most part this book ignores the internal implementation. If you wish to know these details, manytexts exist that cover them. The interface is what this book describes in detail. The majority of UNIX users need to be familiar with the interface and need no

    t understand the internal workings of UNIX.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    12/28

    UNIX is a very powerful and fast operating system and is the only serious competitor to the Microsoft world left in the operating system market. It is also veryold: UNIX dates back into the 1970s. What could be considered a weakness is actually strength: UNIX has been flexible enough to accommodate 30 years worth of hardware and software development and is very likely to continue to do so. The fa

    int hearted are put of by UNIX because of its sometimes cryptic command languageand its complexity. However with an inquisitive mind and playfulness the powerof UNIX can be easily mastered. Eventually you may realize that cryptic commandsactually 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 from the fact that a modern operating system provides so many services to its users. In contrast to Windows, 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 the operation of the UNIX system. The kernel provides the essentialservices that make up the heart of UNIX systems; it allocates memory, keeps track of the physical location of files on the computers hard disks, loads and executes binary programs such as shells, and schedules the task swapping without whichUNIX systems would be incapable of doing more than one thing 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; thisinterface, the system call interface, effectively insulates the other programs on the UNIX 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 itissues a system call which asks the kernel to open the file. The kernel takes over and handles the request, then notifies the program whether the request succeeded or failed. To read data in from the file takes another system call; the kern

    el determines whether or not the request is valid, and if it is, the kernel reads the required block of data and passes it back to the program. Unlike DOS (andsome other

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    13/28

    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 constitutes 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 and administrators. Within any Unix version, there are several different shells which affect how commands are interpreted. Yourdefault is that you are using Solaris (developed by Sun Microsystems primarily for use on hardware sold by Sun) within the c-shell. Most of the basic commands here will work the same in other Unix variants and shells, including Linux and theMac OS X command-line environment. All Unix commands and file references are case sensitive: This is a different filename than this because of the capitalization difference. All Unix commands are lowercase and from two to nine characters long.Many commands have options that are invoked by a hyphen followed by one or moreletters. 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 shell environments.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    14/28

    Wildcards: * is a wildcard character that can refer to any character string and ?is a wildcard 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 255characters, and they may include any character except the regular slash /. (Avoi

    d 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 pathname 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 a shorthand for usernames home directory, .. (two periods) for thesubdirectory one level up from the current directory, and . (one period) for the current directory.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    15/28

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    16/28

    5.

    Describe the following: A) Unix Kernel

    Ans: Most Unix systems implement a two-stage loading process: During the first s

    tage, a small 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 vendordependent. For example, it is /vmunix on SunOS 4.x, Digital Unix and Ultrix, /kernel/unix on SunOS 5.x, or /unix on IRIX andAIX systems. Once the kernel is loaded, it remains 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 thatit cant contact). Any device not detected and initialized during the boot will not be accessible to system until it is properly connected and the system is rebooted. System Processes: The kernel identifies the root, swap, and dump devices and then starts programs to schedule processes, manage physical memory and virtualmemory, and the init process. BSD systems starts three initialization processes

    ; swapper, init and pagedaemon. On the SVR4 systems the initialization processesinclude 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 usedto set priority for real-time processes so that they can be given fast access tothe 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 physical memory is needed. page daemon: Various memory handlers run asprocess 2. When a page of virtual memory is accessed, the page table within thekernel 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 memory and to update page tables. Similar memory handlers exist on other SVR5 systems. init: The last stepin 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 onthe 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 setting the date, checking the consistency of the file system, reconfiguring the list of on-line terminals, and so on. At this stageonly the root partition is usually mounted.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    17/28

    Other file systems will have to be mounted manually to use programs that do notreside on the root volume. The file system consistency check may be performed bythe 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 t

    o interpret them. The startup scripts are defined and organized differently on different systems. On BSD systems the 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 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 to take. 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 levelin which the entry can be processed. If this field is empty, all run levels areassumed. 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/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    18/28

    Configure the network interface. Turn on the accounting and quotas. Shutdown Shutdown command: Notifies users with wall about the system going down. Sleeps fora minute and may give 1 or 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 the system. This login name identifies the user. Whena newuser is added to unix systems systems 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 isalso assigned to a group, group is collection of users in one department or working on one project identified with one group name. Each group 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 positive integer So together UIDand GID determine what kind of access rights a user has to files and directories. Procedures to add a new user to system: Get users name and create a login id ba

    sed 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/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    19/28

    Create a home directory for user, preferably on the same disk where other home directories 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 printingsystem for new user. Test this account. USERADD: Enables a super user or root tocreate 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 commentfield. -d home_dir: The new user will be created using home_dir as the value for the users login directory. -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 permanentlydisabled. A value of 0 disables the account as soon as the password has expired,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 name must exist. The default group no. is 1. -G group,[,...]: A list of supplementary gr

    oups which the user is also a member of. Each group is separated from the next by a comma, with no intervening whitespace.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    20/28

    -m: The users home directory will be created if it does not exist. The files contained in skeleton_dir will be copied to the home directory if the -k option is used, otherwise the files contained in /etc/skel will be used instead. -p passwd:The encrypted password, as returned by crypt. The default is to disable the account. -s shell: The name of the users login shell. The default is to leave this f

    ield blank, which causes 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 option is 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 and99 are typically reserved for system accounts. -b default_home: The initial pathprefix for a new users home directory. The users name will be affixed to the endof default_home to create the new directory name if the -d option is not used 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 hasexpired before the account will be disabled. -g default_group: The group name orID 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 l

    ogin 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 option is used. The value must be non-negative. The default is to use the smallestID value greater than 99 and greater than every other group. Values between 0 and 99 are typically reserved for system accounts USERDEL: Enables a super user to remove a users account. userdel [-r] login

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    21/28

    -r: Files in the users home directory will be removed along with the home directory itself and the 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 in10 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. SYNTA

    X 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 file contains the username, real name, identification information, and basic account information for each user. Each line in the file contains a database record;the record fields are separated by a colon (:). You can use the cat command to display your systems /etc/passwd file. Here are a few sample lines from a typicalfile: 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 individualusers. The individual fields of the /etc/passwd file are: Field Contents

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    22/28

    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 the file. Encrypted passwords may also be stored in separate shadow passwor

    d 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 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 maybe changed (0 indicates it may be changed at any time). 99999: The no. of daysafter 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 disabled1075502268: Not presently used. The shadow password file is kept in different places for different types of Unixes. The example given (/etc/shadow) is for a Re

    dhat based linux system. The format of the shadow file also varies from system to system.

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    23/28

    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 fromone of them to the other one. If we want a two-way communication, well need twopipes. The system assures us of one thing: The order in which data is written tothe pipe, is the same order as that in which data is read from the pipe. The system also assures that data wont get lost in the middle, unless one of the processes (the sender or the receiver) exits prematurely. The pipe() System Call: Thissystem call is used to create a read-write pipe that may later be used to communicate with a process well fork off. The call takes as an argument an array of 2integers that will be used to save the two file descriptors used to access the p

    ipe. The first to read from the pipe, and the second to write to the pipe. Hereis how to use this function: /* first, define an array to store the two file descriptors */ int pipes[2]; int rc = pipe(pipes); if (rc == -1) { perror("pipe");exit(1); } #include #include /* defines pipe(), amongst other things. */ /* pipe() failed */ /* now, create the pipe */

    /* this routine handles the work of the child process. */ void do_child(int data_pipe[]) { int c; int rc; /* data received from the parent. */ /* return statusof read(). */

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    24/28

    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); } /* this routine handles the work of the parent process. */ void do_parent(int data_pipe[]) { int c; int rc; close(data_pipe[0]); /* data received from the user. */ /* return status of getchar(). */ //close the un-needed read-part of pipe. //may be pipe was broken, or got EOF via the 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); if (rc == -1) { perror("Parent: write"); close(data_pipe[1]); exit(1); } } close(data_pipe[1]); /* probably got EOF from the user. //write character to the pipe. // write failed notify the userand exit

    /* 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/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    25/28

    int pid; int rc; rc = pipe(data_pipe); if (rc == -1) { perror("pipe"); exit(1);} pid = fork();

    // pid of child process, or 0, as returned via fork. // stores return values ofvarious routines. // first, create a pipe.

    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 file 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 for writing. The same goes the other way around. Creating A Named Pipe: A named pipe maybe 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 t

    he following command: mknod prog_pipe p We could also provide a full path to where we want the named pipe created. If we then type ls -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 has accesspermissions, that define which users may open the named pipe, and whether for reading, writing or both. C) Message Queues

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    26/28

    Ans: A message queue is a queue onto which messages can be placed. A message iscomposed of 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 byits 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 the queue. Messages may beread by type, and thus not have to be read in a FIFO order as is the case with pipes. Creating A Message Queue msgget(): In order to use a message queue, it hasto be created first. The msgget() system call is used to do just that. This system call accepts two parameters 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. It may 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 #include #include #include /* standard I/O routines. */ /* standard system data types. /* common system V IPC structures. */ /* mes

    sage-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 identifyingthe created queue. Later on we can use this key in order to access the queue forreading and writing messages. 2. The queue created belongs to the user whose process created the queue. Thus, since the permission bits are 0600, only processesrun on behalf of this user will have access to the queue. D) Message Structure

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    27/28

    Ans: Before we go to writing messages to the queue or reading messages from it,we need to see how a message looks. The system defines a structure named msgbuf for this purpose. Here is how it is defined: struct msgbuf { long mtype; char mtext[1]; one byte. */ }; Lets create an "hello world" message: /* first, define themessage string */ char* msg_text = "hello world"; /* allocate a message with en

    ough space for length of string and */ /* one extra byte for the 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; */ strcpy(msg->mtext, msg_text); /* finally, place the "hello world" string inside the message. /* message type, a positive number (cannot be zero). *//* message body array. usually larger than

  • 8/3/2019 53252878 MC0070 August 2010 Operating Systems With Unix

    28/28