Top Banner
Master of Computer Application (MCA) – Semester 2 MC0070 – Operating Systems with UNIX Assignment Set – 1 Que 1. 1. Describe the following operating system components: A)Functions of an Operating system B) Operating system components Ans: Functions of an Operating System Modern Operating systems generally have following three major goals. Operating 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. (1) 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 control 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 1
34

(MC0070)operating system

Oct 14, 2014

Download

Documents

Hemant Soni

download MCA 2nd sem and 3rrd sem assignment (7737397502)
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: (MC0070)operating system

Master of Computer Application (MCA) – Semester 2

MC0070 – Operating Systems with UNIX

Assignment Set – 1

Que 1. 1. Describe the following operating system components:

A) Functions of an Operating system B) Operating system components

Ans:

Functions of an Operating System

Modern Operating systems generally have following three major goals. Operating 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.

(1)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 control 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.

1

Page 2: (MC0070)operating system

(2) Resources Management

An operating system as resource manager, controls how processes (the active agents) may access resources (passive entities). One can view Operating Systems from two points of views: Resource manager and Extended machines. Form Resource manager point of view Operating Systems manage the different parts of the system efficiently and from extended machines point of view Operating Systems provide a 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.

(3) Provide a effective user interface

The user interacts with the operating systems through the user interface and usually interested in the look and feel of the operating system. The most important components 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 interfaces that encompass the activities of multiple processes on networks of computers.

Operating System Components

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

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

a process is not a program. A process is only ONE instant of a program in execution. 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.

2

Page 3: (MC0070)operating system

5. A mechanism for deadlock handling

(2) Main-Memory Management

(1) 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 be access directly by the CPU. That is to say for a program to be executed, it must in the main memory.

(2) The major activities of an operating in regard to memory-management are:(3) 1. Keep track of which part of memory is currently being used and by whom.

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

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

(3) File Management

A file is a collection of related information defined by its creator. Computer can store files on the disk (secondary storage), which provides long 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 into directories to ease their use. These directories may contain 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.

(4). I/O System Management

3

Page 4: (MC0070)operating system

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

(5). Secondary-Storage Management

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 its data are lost when power is lost, the computer system must provide secondary storage to back up main memory. Secondary storage consists of tapes, disks, and other media designed to hold information that 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 storage management are:

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

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

3. Scheduling the requests for memory access.

(5). Networking

A distributed system is a collection of processors that do not share memory, peripheral devices, or a clock. The processors communicate with one another through communication lines called network. The communication-network design must consider routing and connection strategies, and the problems of contention and security.

(6). Protection System

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

(7). Command Interpreter System

4

Page 5: (MC0070)operating system

A command interpreter is an interface of the operating system 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 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 interface of command interpreter, I am able to do that if the command interpreter is separate from the kernel. I cannot change the code of the kernel so I cannot modify the interface.

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

Que 2. Describe the following:

A. Micro Kernels

B. Modules

Ans:

A.Micro-kernels

We have already seen that as UNIX expanded, the kernel became large and difficult to manage. In the mid-1980s, researches at Carnegie Mellon University developed an operating system called Mach that modularized the kernel using the microkernel approach. This method structures the operating system by removing all nonessential components from the 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 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

File Server

Client Process

…. Virtual Memory

5

Page 6: (MC0070)operating system

Microkernel

Hardware

Fig. 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 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 user space and consequently do not require modification of the kernel. When the kernel does have to be modified, the changes tend to be fewer, because the microkernel is a smaller kernel. The resulting operating system is easier to 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.

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 a March kernel. The March kernel maps UNIX system calls into messages to the appropriate user-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

6

Page 7: (MC0070)operating system

Fig. UNIX Architecture

B. Modules

Perhaps the best current methodology for operating-system design involves using object-oriented programming techniques to create a modular kernel. Here, the kernel has a set 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, such as Solaris, Linux and MacOSX. For example, the Solaris operating system structure is organized around a core kernel with seven types of loadable kernel modules:

1. Scheduling classes

2. File systems

3. Loadable system calls

4. Executable formats

5. STREAMS formats

6. Miscellaneous

7. Device and bus drivers

7

Page 8: (MC0070)operating system

Such a design allow the kernel to provide core services yet also allows certain features to be implemented dynamically. For example device and bus drivers for specific 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 with other modules; but it is more efficient, because modules do not need to invoke message passing in order to communicate.

.

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

Ans:

Process Control

In this section we will study structure of a process, process control block, modes of process execution, and process switching.

Process Structure

After studying the process states now we will see where does the process reside, and 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 it is brought in the main memory, and for that the operating system need to know the location of the process.

Process identification

Processor state information

Process control information

User Stack

8

Page 9: (MC0070)operating system

Private user address space (program, data)

Shared address space

Figure: 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 a process; System Stack, which is used to store parameters and calling addresses for procedure and system calls, and Process Control Block, this is nothing but collection of process attributes needed by operating system to control a process. The collection of user program, data, system stack, and process control block is called as Process Image as shown in the figure 3.3 above.

Process Control Block

A process control block as shown in the figure 3.4 bellow, contains various attributes 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 who’s this process is being run.

The Processor state information consists of the contents of the processor registers, such as user-visible registers, control and status registers which includes program counter and program status word, and stack pointers.

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

pointer process state

9

Page 10: (MC0070)operating system

process number

program counter

registers

memory limits

list of open files

.

.

.

Figure: Process Control Block

Modes of Execution

In order to ensure the correct execution of each process, an operating system must protect each process’s private information (executable code, data, and stack) from uncontrolled interferences from other processes. This is accomplished by suitably restricting 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 process violates those restrictions.

Also the OS 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 this mode, 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 to be executed in privileged mode. After the completion of system call or interrupt routine, the mode is again changed to user mode to continue the user process execution.

Context Switching

To give each process on a multiprogrammed machine a fair share of the CPU, a hardware clock generates interrupts periodically. This allows the operating system to schedule all processes in main memory (using scheduling algorithm) to run on the CPU at equal

10

Page 11: (MC0070)operating system

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 CPU’s 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 the progression of one process and storing the CPU’s state (i.e., the context) for that process somewhere in memory, (2) retrieving the context of the next process from memory and restoring it in the CPU’s 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.

Figure: Process switching

11

Page 12: (MC0070)operating system

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

Ans:

Hardware Management

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. If you shut down the computer, the operating system also has a procedure that makes sure all the hardware is shut down correctly. Before turning your computer off again, 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.

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. 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 to manage them.

Table 1.1. Operating system functions

Action OS Does This

You turn on the computer Hardware management

You execute an application Process management

Application reads a tape Hardware management

Application waits for data Process management

Process waits while other process runsProcess management

Process displays data on screen Hardware management

Process writes data to tape Hardware management

You quit, the process terminates Process management

12

Page 13: (MC0070)operating system

You turn off the computer Hardware management

From the time you turn on your computer until you turn it off, the operating system is coordinating the operations. As hardware is initialized, accessed, or shut down, the operating system 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.

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 essential services that make up the heart of UNIX systems; it allocates memory, keeps track of the physical location of files on the computer’s hard disks, loads and executes binary programs such as shells, and schedules the task swapping without which UNIX 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; this interface, the system call interface, effectively insulates the other programs on the UNIX system from the complexities of the computer. For example, when a running

13

Page 14: (MC0070)operating system

program needs access to a file, it cannot simply open the file; instead it issues 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 kernel 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 (and some other 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. Your default 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 the Mac OS X command-line environment

A standard Unix system provides commands username, passwd, chsh, and additional options on chdgrp to change usernames, passwords, default groups, and shell environments.

Wildcards: * is a “wildcard” character that can refer to any character string and ? is 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 255 characters, and they may include any 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 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 username’s home directory, .. (two periods) for the subdirectory one level up from the current directory, and . (one period) for the current directory.

Que .5. Describe the following:A) Unix KernelB) Unix Startup Scripts

Ans:

14

Page 15: (MC0070)operating system

Kernel

Most Unix systems implement a two-stage loading process: During the first stage, 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 vendor-dependent. For example, it is /vmunix on SunOS 4.x, Digital Unix and Ultrix, /kernel/unix on SunOS 5.x, or /unix on IRIX and AIX systems. Once the kernel is loaded, 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 that it can’t 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 kernels identifies the root, swap, and dump devices and then starts programs to schedule processes, manage physical memory and virtual memory, and the init process. BSD systems starts three initialization processes; swapper, init and pagedaemon. On the SVR4 systems the initialization processes include sched, init, and various memory handlers (except on Solaris).

sched: The real-time scheduler, sched, runs as process 0 on SVR5 systems. It can be used to 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 physical memory is needed.

page daemon: Various memory handlers run as process 2. When a page of virtual memory is 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 memory and 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 runs as 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 setting the date, checking the consistency of the file system, reconfiguring the list of on-line terminals, and so on. At this stage only the root partition is usually mounted.

15

Page 16: (MC0070)operating system

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

Startup Scripts:-

The startup scripts are merely shell scripts, so init spawns a copy of sh to 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 level in which the entry can be processed. If this field is empty, all run 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 entry’s 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 system’s disk partitions.

Start the daemons and network services.

Configure the network interface.16

Page 17: (MC0070)operating system

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 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. When a 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 is also 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 UID and GID determine what kind of access rights a user has to files and directories.

Procedures to add a new user to system:

· Get user’s 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.

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

17

Page 18: (MC0070)operating system

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

· 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 user’s password file comment field.

-d home_dir: The new user will be created using home_dir as the value for the user’s 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 permanently disabled. 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 user’s initial login group. The group name must exist. The default group no. is 1.

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

-m: The user’s 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 user’s login shell. The default is to leave this field blank, which causes the system to select the default login shell.

18

Page 19: (MC0070)operating system

-u uid: The numerical value of the user’s 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 and 99 are typically reserved for system accounts.

-b default_home: The initial path prefix for a new user’s home directory. The user’s name will be affixed to the end of 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 has expired before the account will be disabled.

-g default_group: The group name or ID for a new user’s 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 user’s 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 group’s 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 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

-r: Files in the user’s home directory will be removed along with the home directory itself and the user’s mail spool.

EXIT VALUES

0 – success 1 – can’t update password file 2 – bad command syntax 6 – specified user doesn’t exist 8 – user currently logged in 10 – can’t update group file 12 – can’t remove home directory

EXAMPLE: userdel -r newperson

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

19

Page 20: (MC0070)operating system

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 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 system’s /etc/passwd file. Here are a few sample 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

Rachel The username

EH5/.mj7NB3dx the user’s "encrypted password"

181 User’s user identification number (UID)

100 User’s group identification number (GID)

Rachel Cohen The user’s full name

/u/rachel The user’s home directory

/bin/ksh The user’s 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 password files

20

Page 21: (MC0070)operating system

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 user’s 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 any time).

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

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

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

Que 6. Explain the following with respect to Interprocess communication in Unix:A) Communication via pipesB) Named PipesC) Message QueuesD) Message Structure

Ans:-

A) Communication via pipes

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, we’ll need two pipes. The system assures us of one thing: The order in which data is written to the pipe, is the same order as that in which data is read from the pipe. The system also assures that data won’t get lost in the middle, unless one of the processes (the sender or the receiver) exits prematurely.

B) Named Pipes21

Page 22: (MC0070)operating system

Named Pipe

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

C) Message Queues

A message queue is a queue onto which messages can be placed. A message is composed 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 by its creating process or child processes of that creator. If it’s public, it can be accessed by any process that knows the queue’s key.

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

Creating A Message Queue – msgget()

22

Page 23: (MC0070)operating system

In order to use a message queue, it has to 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.

D) Message Structure

Message Structure – struct msgbuf

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; /* message type, a positive number (cannot be

zero). */

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

one byte. */

}; Lets create an "hello world" message:

/* first, define the message string */

char* msg_text = "hello world";

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

23

Page 24: (MC0070)operating system

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

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

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

strcpy(msg->mtext, msg_text);

3.6.5.1 Writing Messages Onto A Queue – msgsnd()

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

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

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

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

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

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

to set no flags, use the value ‘0′.

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

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

if (rc == -1) {

perror("msgsnd");

exit(1);

}

3.6.5.2 Reading A Message From The Queue – msgrcv()

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

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

24

Page 25: (MC0070)operating system

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

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

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

0 – The first message on the queue will be returned.

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

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

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

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

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

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

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

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

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

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

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

25