You are on page 1of 30

Features of Unix OS:

➢Multi-user, multitasking operating system


➢It can be used as the master control program in workstations and
servers.
➢Hundreds of commercial applications are available
➢In its heydays, UNIX was rapidly adopted and became the standard OS
in universities

Features of Linux OS:


➢Support multitasking
➢Programs consist of one or more processes, and each process have
one or more threads
➢It can easily co-exists along with other Operating systems.
➢It can run multiple user programs
➢Individual accounts are protected because of appropriate
authorization
➢Linux is a replica of UNIX but does not use its code
Unix Architecture:-
Here is a basic block diagram of a Unix system −

The main concept that unites all the versions of Unix is the following
four basics −
Kernel − The kernel is the heart of the operating system. It interacts with
the hardware and most of the tasks like memory management, task
scheduling and file management.

Shell − The shell is the utility that processes your requests. When you
type in a command at your terminal, the shell interprets the command and
calls the program that you want. The shell uses standard syntax for all
commands. C Shell, Bourne Shell and Korn Shell are the most famous shells
which are available with most of the Unix variants.

Commands and Utilities − There are various commands and utilities


which you can make use of in your day to day activities. cp, mv, cat and
grep, etc. are few examples of commands and utilities. There are over 250
standard commands plus numerous others provided through 3 rd party
software. All the commands come along with various options.

Files and Directories − All the data of Unix is organized into files. All
files are then organized into directories. These directories are further
Linux Operating System has primarily three components
Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this
operating system. It consists of various modules and it interacts directly with the
underlying hardware. Kernel provides the required abstraction to hide low level
hardware details to system or application programs.
System Library − System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These libraries
implement most of the functionalities of the operating system and do not requires
kernel module's code access rights.
System Utility − System Utility programs are responsible to do specialized, individual
level tasks.
Linux System Architecture:-

The architecture of a Linux System consists of the following layers −

Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
Kernel − It is the core component of Operating System, interacts directly with
hardware, provides low level services to upper layer components.
Shell − An interface to kernel, hiding complexity of kernel's functions from users. The
shell takes commands from the user and executes kernel's functions.
Utilities − Utility programs that provide the user most of the functionalities of an
operating systems.
ESSENTIAL UNIX Commands:-
Command Example Description

1. ls ls Lists files in current directory


ls -alF List in long format

2. cd cd tempdir Change directory to tempdir


cd .. Move back one directory
cd ~dhyatt/web-docs Move into dhyatt's web-docs directory

3. mkdir mkdir graphics Make a directory called graphics

4. rmdir rmdir emptydir Remove directory (must be empty)

5. cp cp file1 web-docs Copy file into directory


cp file1 file1.bak Make backup of file1

6. rm rm file1.bak Remove or delete file


rm *.tmp Remove all file

7. mv mv old.html new.html Move or rename files

8. more more index.html Look at file, one page at a time

9. lpr lpr index.html Send file to printer

10. man man ls Online manual (help) about command


VALUABLE
Command UNIX Commands:-
Example Description

1. grep <str><files> grep "bad word" * Find which files contain a certain word

2. chmod <opt> chmod 644 *.html Change file permissions read only
<file> chmod 755 file.exe Change file permissions to executable

3. passwd passwd Change passwd

4. ps <opt> ps aux List all running processes by #ID


ps aux | grep dhyatt List process #ID's running by dhyatt

5. kill <opt> <ID> kill -9 8453 Kill process with ID #8453

6. gcc (g++) gcc file.c -o file Compile a program written in C


<source> g++ fil2.cpp -o fil2 Compile a program written in C++

7. gzip <file> gzip bigfile ; gunzip bigfile.gz Compress file ; Uncompress file

8. mail mail me@tjhsst.edu < file1 Send file1 by email to someone


(pine) pine Read mail using pine

9. telnet <host> telnet vortex.tjhsst.edu Open a connection to vortex


ssh <host> ssh -l dhyatt jazz.tjhsst.edu Open a secure connection to jazz as user
dhyatt

10. ftp <host> ftp station1.tjhsst.edu Upload or Download files to station1


FUN UNIX Commands:-
Command Example Description

1. who who Lists who is logged on your machine

2. finger finger Lists who is on computers in the lab

3. ytalk <user@place> ytalk dhyatt@threat Talk online with dhyatt who is on threat

4. history history Lists commands you've done recently

5. fortune fortune Print random humerous message

6. date date Print out current date

7. cal <mo> <yr> cal 9 2000 Print calendar for September 2000

8. xeyes xeyes & Keep track of cursor (in "background")

9. xcalc xcalc & Calculator ("background" process)

10. mpage <opt> <file> mpage -8 file1 | lpr Print 8 pages on a single sheet and send
to printer (the font will be small!)
HELPFUL UNIX Commands:-
Command Example Description

1. netscape netscape & Run Netscape browser

2. xv xv & Run graphics file converter

3. xfig / xpaint xfig & (xpaint &) Run drawing program

4. gimp gimp & Run photoshop type program

5. ispell <fname> ispell file1 Spell check file1

6. latex <fname> latex file.tex Run LaTeX, a scientific document tool

7. xemacs / pico xemacs (or pico) Different editors

8. soffice soffice & Run StarOffice, a full word processor

9. m-tools (mdir, mcopy, mdir a: DOS commands from UNIX (dir A:)
mdel, mformat, etc. ) mcopy file1 a: Copy file1 to A:

10. gnuplot gnuplot Plot data graphically


USEFUL UNIX Commands:-
Command Example Description

1. df df See how much free disk space

2. du du -b subdir Estimate disk usage of directory in Bytes

3. alias alias lls="ls -alF" Create new command "lls" for long format of

4. xhost xhost + threat.tjhsst.edu Permit window to display from x-window


xhost - program from threat
Allow no x-window access from other system

5. fold fold -s file1 | lpr Fold or break long lines at 60 characters and
send to printer

6. tar tar -cf subdir.tar subdir Create an archive called subdir.tar of a


tar -xvf subdir.tar directory
Extract files from an archive file

7. ghostview (gv) gv filename.ps View a Postscript file

8. ping ping threat.tjhsst.edu See if machine is alive


(traceroute) traceroute www.yahoo.com Print data path to a machine

9. top top Print system usage and top resource hogs

10. logout (exit) logout or exit How to quit a UNIX shell.


File Management in Unix:-
➢All data in Unix is organized into files. All files are organized into directories.
➢These directories are organized into a tree-like structure called the file
system.
➢When you work with Unix, one way or another, you spend most of your time
working with files. This chapter will help you understand how to create and
remove files, copy and rename them, create links to them, etc.

In Unix, there are three basic types of files −

Ordinary Files − An ordinary file is a file on the system that contains data, text,
or program instructions. In this, you look at working with ordinary files.

Directories − Directories store both special and ordinary files. For users familiar
with Windows or Mac OS, Unix directories are equivalent to folders.

Special Files − Some special files provide access to hardware such as hard
drives, CD-ROM drives, modems, and Ethernet adapters. Other special files are
similar to aliases or shortcuts and enable you to access a single file using
different names.
Listing Files:-
To list the files and directories stored in the current directory, use the following
command −
$ls
Here is the sample output of the above command −
$ls
bin hosts lib res.03
ch07 hw1 pub test_results
ch07.bak hw2 res.01 users
docs hw3 res.02 work
The command ls supports the -l option which would help you to get more
information about the listed files −
$ls -l
total 1962188
drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 27648 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
$
Here is the information about all the listed columns −

First Column − Represents the file type and the permission given on
the file. Below is the description of all type of files.
Second Column − Represents the number of memory blocks taken by
the file or directory.
Third Column − Represents the owner of the file. This is the Unix user
who created this file.
Fourth Column − Represents the group of the owner. Every Unix user
will have an associated group.
Fifth Column − Represents the file size in bytes.
Sixth Column − Represents the date and the time when this file was
created or modified for the last time.
Seventh Column − Represents the file or the directory name.
In the ls -l listing example, every file line begins with a d, -,
or l. These characters indicate the type of the file that's listed.

Sr.No. Prefix & Description


1 - Regular file, such as an ASCII text file, binary
executable, or hard link.
2 B Block special file. Block input/output device file such
as a physical hard drive.
3 C Character special file. Raw input/output device file
such as a physical hard drive.
4 D Directory file that contains a listing of other files and
directories.
5 L Symbolic link file. Links on any regular file.
6 P Named pipe. A mechanism for interprocess
communications.
7 S Socket used for interprocess communication.
Metacharacters:-

Metacharacters have a special meaning in Unix. For example, * and ? are


metacharacters. We use * to match 0 or more characters, a question
mark (?) matches with a single character.
For Example −
$ls ch*.doc

Displays all the files, the names of which start with ch and end
with .doc −
ch01-1.doc ch010.doc ch02.doc ch03-2.doc
ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc c
Here, * works as meta character which matches with any character. If
you want to display all the files ending with just .doc, then you can use
the following command −
$ls *.doc
Hidden Files:-
Some common examples of the hidden files include the files −
.profile − The Bourne shell ( sh) initialization script
.kshrc − The Korn shell ( ksh) initialization script
.cshrc − The C shell ( csh) initialization script
.rhosts − The remote shell configuration file

To list the invisible files, specify the -a option to ls −

$ ls –a
. .profile docs lib test_results
.. .rhosts hosts pub users
.emacs bin hw1 res.01 work
.exrc ch07 hw2 res.02
.kshrc ch07.bak hw3 res.03
$
Single dot (.) − This represents the current directory.
Double dot (..) − This represents the parent directory.
Creating Files:-
You can use the vi editor to create ordinary files on any Unix system. You
simply need to give the following command −

$ vi filename

The above command will open a file with the given filename. Now, press
the key i to come into the edit mode. Once you are in the edit mode,
you can start writing your content in the file as in the following program

This is unix file....I created it for the first time.....
I'm going to save this content in this file.
Once you are done with the program, follow these steps −
Press the key esc to come out of the edit mode.
Press two keys Shift + ZZ together to come out of the file completely.
You will now have a file created with filename in the current directory.
$ vi filename
$
Editing Files:-
You can edit an existing file using the vi editor. We will discuss in short how to
open an existing file −
$ vi filename
Once the file is opened, you can come in the edit mode by pressing the key I
and then you can proceed by editing the file. If you want to move here and
there inside a file, then first you need to come out of the edit mode by
pressing the key Esc. After this, you can use the following keys to move inside a
file −

l key to move to the right side.


h key to move to the left side.
k key to move upside in the file.
j key to move downside in the file.

So using the above keys, you can position your cursor wherever you want to
edit. Once you are positioned, then you can use the i key to come in the edit
mode. Once you are done with the editing in your file, press Esc and finally two
keys Shift + ZZ together to come out of the file completely.
Display Content of a File:-
You can use the cat command to see the content of a file. Following is a simple example to see
the content of the above created file −
$ cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
$
You can display the line numbers by using the -b option along with the catcommand as follows −
$ cat -b filename
1 This is unix file....I created it for the first time.....
2 I'm going to save this content in this file.
$
Counting Words in a File:-
You can use the wc command to get a count of the total number of lines, words, and characters
contained in a file. Following is a simple example to see the information about the file created
above −
$ wc filename
2 19 103 filename
$
Here is the detail of all the four columns −
First Column − Represents the total number of lines in the file.
Second Column − Represents the total number of words in the file.
Third Column − Represents the total number of bytes in the file. This is the actual size of the file.
Fourth Column − Represents the file name.
$ wc filename1 filename2 filename3
Copying Files:-
To make a copy of a file use the cp command. The basic syntax is −
$ cp source_file destination_file
Following is the example to create a copy of the existing file filename.
$ cp filename copyfile
$
Renaming Files:-
To change the name of a file, use the mv command. Basic syntax −
$ mv old_file new_file
The following program will rename the existing file filename to newfile.
$ mv filename newfile
$
Deleting Files:-
To delete an existing file, use the rm command. Following is the basic syntax −
$ rm filename
It is better to use the -i option along with rm command.
example which shows how to completely remove the existing file filename.
$ rm filename
$
You can remove multiple files at a time with the command given below −
$ rm filename1 filename2 filename3
File Descriptors:
➢ Tothe kernel, all open files are referred to by file descriptors.
➢ A file descriptor is a non-negative integer. When we open an existing file
or create a new file, the kernel returns a file descriptor to the process.
➢ When we want to read or write a file, we identify the file with the file
descriptor that was returned by open or create as an argument to either
read or write.
open and openat Functions:
➢ A file is opened or created by calling either the open function or the
openat function.

#include <fcnt1.h>
int open(const char *path, int oflag, ... /* mode_t mode */ );
int openat(int fd, const char *path, int oflag, ... /* mode_t mode */ );

O_RDONLY Open for reading only. O_WRONLY Open for writing only.
O_RDWR Open for reading and writing. O_EXEC Open for execute only.
O_SEARCH Open for search only (applies to directories).
creat Function:-
A new file can also be created by calling the creat function.

#include <fcnt1.h>
int creat(const char *path, mode_t mode);

Note that this function is equivalent to


open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);

close Function:-
An open file is closed by calling the close function.

#include <fcnt1.h>
int close(int fd);
lseek Function:-
Every open file has an associated ‘‘current file offset,’’ normally a non-
negative integer that measures the number of bytes from the beginning of
the file.
An open file’s offset can be set explicitly by calling lseek.
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
The interpretation of the offset depends on the value of the whence
argument.
• If whence is SEEK_SET, the file’s offset is set to offset bytes from the
beginning of the file.
• If whence is SEEK_CUR, the file’s offset is set to its current value plus the
offset. The offset can be positive or negative.
• If whence is SEEK_END, the file’s offset is set to the size of the file plus the
offset. The offset can be positive or negative.
Because a successful call to lseek returns the new file offset, we can seek
zero bytes from the current position to determine the current offset:
off_t currpos;
currpos = lseek(fd, 0, SEEK_CUR);
This technique can also be used to determine if a file is capable of seeking.
read Function:-
Data is read from an open file with the read function.
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes);
If the read is successful, the number of bytes read is returned. If the end of
file is encountered, 0 is returned.
There are several cases in which the number of bytes actually read is less
than the amount requested:
• When reading from a regular file, if the end of file is reached before the
requested number of bytes has been read. The next time we call read, it
will return 0 (end of file).
• When reading from a terminal device. Normally, up to one line is read at
a time.
• When reading from a network. Buffering within the network may cause
less than the requested amount to be returned.
• When reading from a pipe or FIFO.
• When reading from a record-oriented device. Some record-oriented
devices, such as magnetic tape, can return up to a single record at a time.
• When interrupted by a signal and a partial amount of data has already
been read.
write Function:-
Data is written to an open file with the write function.
#include< unistd.h>
ssize_t write(int fd, const void *buf, size_t nbytes);
The return value is usually equal to the nbytes argument; otherwise, an
error has occurred.

➢A common cause for a write error is either filling up a disk or exceeding


the file size limit for a given process.
➢For a regular file, the write operation starts at the file’s current offset.
➢After a successful write, the file’s offset is incremented by the number of
bytes actually written.
Definition of fork():
An existing process can create a new one by calling the fork function.
#include <unistd.h> pid_t fork(void);
➢The fork() is a system call use to create a new process.
➢The new process created by the fork() call is the child process, of the process
that invoked the fork() system call.
➢The code of child process is identical to the code of its parent process. After
the creation of child process, both process i.e. parent and child process start
their execution from the next statement after fork() and both the processes
get executed simultaneously.
➢The parent process and child process do have separate address space.
Hence, when any of the processes modifies any statement or variable in the
code. It would not be reflected in other process codes. Let’s suppose if child
process modifies the code it would not affect the parent process.
➢Some child process after their creation immediately calls exec(). The exec()
system call replaces the process with the program specified in its parameter.
Then the separate address space of child process is of no use. The one
alternative here is copy-on-write.
➢The copy-on-write let the parent and child process to share same address
space. If the any of the processes writes on the pages in address space the
Definition of vfork():

➢The modified version of fork() is vfork().


➢The vfork() system call is also used to create a new process. Similar to the
fork(), here also the new process created is the child process, of the
process that invoked vfork().
➢The child process code is also identical to the parent process code. Here,
the child process suspends the execution of parent process till it
completes its execution as both the process share the same address
space to use.
➢As the child and parent process shares the same address space. If any of
the processes modifies the code, it is visible to the other process sharing
the same pages. Let us suppose if the parent process alters the code; it
will reflect in the code of child process.
➢As using vfork() does not create separate address spaces for child and
parent processes. Hence, it must be implemented where the child
process calls exec() immediately after its creation. So, there will be no
wastage of address space, and it is the efficient way to create a
process. vfork does not use copy-on-write.
exit Function:-
A process can terminate normally in five ways:
1. Executing a return from the main function.
2. Calling the exit function.
3. Calling the _exit or _Exit function.
4. Executing a return from the start routine of the last thread in the process.
5. Calling the pthread exit function from the last thread in the process.

The three forms of abnormal termination are as follows:


1. Calling abort. This is a special case of the next item, as it generates the
SIGABRT signal.
2. When the process receives certain signals. The signal can be generated by
the process itself (e.g., by calling the abort function), by some other
process, or by the kernel. Examples of signals generated by the kernel
include the process referencing a memory location not within its address
space or trying to divide by 0.
3. The last thread responds to a cancellation request. By default, cancellation
occurs in a deferred manner: one thread requests that another be
cancelled, and sometime later the target thread terminates.
wait and waitpid Functions:-
we need to be aware that a process that calls wait or waitpid can
• Block, if all of its children are still running
• Return immediately with the termination status of a child, if a child has
terminated and is waiting for its termination status to be fetched
• Return immediately with an error, if it doesn’t have any child processes.

If the process is calling wait because it received the SIGCHLD signal, we


expect wait to return immediately. But if we call it at any random point in
time, it can block.
#include <sys/wait.h>
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);

The differences between these two functions are as follows:


• The wait function can block the caller until a child process terminates,
whereas waitpid has an option that prevents it from blocking.
• The waitpid function doesn’t wait for the child that terminates first; it has
a number of options that control which process it waits for.
exec Functions:-
The process ID does not change across an exec, because a new process is
not created; exec merely replaces the current process — its text, data,
heap, and stack segments — with a brand-new program from disk.
➢There are seven different exec functions, but we’ll often simply refer to
“the exec function”.
#include<unistd.h>
int execl(const char *pathname, const char *arg0, ... /* (char *)0 */ );
int execv(const char *pathname, char *const argv[]);
int execle(const char *pathname, const char *arg0, ... /* (char *)0, char
*const envp[] */ );
int execve(const char *pathname, char *const argv[], char *const envp[]);
int execlp(const char *filename, const char *arg0, ... /* (char *)0 */ );
int execvp(const char *filename, char *const argv[]);
int fexecve(int fd, char *const argv[], char *const envp[]);
When a filename argument is specified,
• If filename contains a slash, it is taken as a pathname.
• Otherwise, the executable file is searched for in the directories specified
by the PATH environment variable.

You might also like