Unix Imp Questions

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 20

Unix Kernel

UNIX Kernel is heart of the operating system. UNIX kernal is loaded first when UNIX system is
booted. It handles allocation of devices, cpu, memory from that ponint on.

Kernal is the heart of UNIX operating system, it works as interface between the Shell & the
hardware converts user given code into machine understandable language.

What is the difference between Daemon & Server process


A daemon is a software process that runs in the background (continuously) and provides the
service to client upon request. For example named is a daemon. When requested it will provide
DNS service. Other examples are:

xinetd (it is a super-daemon, it is responsible for invoking other Internet servers when they are
needed)
inetd (same as xinetd, but with limited configuration options)
sendmail/postfix (to send/route email)
Apache/httpd (web server)

Following simple example illustrate relationship between client and daemon.

CLIENT -> Daemon

Browser Running one daemon for each of the services could significantly increase the load.
However if you are running big site (with many user) it is advisable to use dedicated daemon. For
example web server or MySQL database server.

A server process run runs one time, when called by a daemon. Once done it will stop. For
example telnetd (in.telnetd) or ftpd called from xinetd/inetd daemon. By calling server process
from daemon you can save the load and memory. Use a server process for small services such
as ftpd, telnetd

CLIENT -> Daemon -> Calls server process


ftp -> xinetd -> Calls ftpd
ftp xinetd stops ftpd
quit

How do you connect to or query Oracle database from a UNIX platform.?


We can connect to Oracle from Unix just by giving the command sqlplus at the prompt and log
into Oracle using the appropriate username and password.

By writing the shell script we can directly connected to oracle


#!/user/bin/bash
sqlplus "/as sysdba"
connect
SELECT distinct contactname,address FROM customers;
shutdown immediate

OR
sqlplus -s userid/password@database
In case you want to connect to SQL database
sqsh -S Servername -U username -P password
In case od SYBASE
isql -S Servername -U username -P password
what is difference between fork() and vfork()?
you should refer to a man page. both create a child process.
fork - parent and child are in 'running' status. they share all page tables until one of them does a
write, then on-demand paging will create private page copy of the dirty page for the modifying
process.
vfork - parent is suspended until child exits or exec's. mainly memory and stack are shared to the
child.
underneath, they both are implemented using the same system call clone, except the flags to
clone differ. which in-turn cause the process status and semantics to change as noted above.
Or
vfork() differs from fork() only in that the child process can share code and data with the calling
process (parent process). This speeds cloning activity significantly at a risk to the integrity of the
parent process if vfork() is misused.
vfork() is a higher performance version of fork() that is provided on some systems where a
performance advantage can be attained.

What is the difference between function call and system call?


function call is generally within the same protection space (ie. user mode to user mode or kernel
mode to kernel mode).
system call is when your process moves across boundaries (ie. user mode to kernel mode)

you can think of the functions you generally write/use from libc/libc++ as function calls. you can
think of clone, read etc as system calls. your library call will setup appropriate values and call a
special CPU instr to jump to the kernel mode, where a table lookup for the requested system call
is performed and code jumps there.

Why is the . not included in the path?


Because . denotes the hidden files in the Unix environment. it is treated as the property of the file
name and is not a part of the path.

Wrong...the dot is not supposed to be in your path because when you enter a command, your
environment i.e. your path will try and execute from your pwd which is never a good thing.

Yes, . means current working directory and having current directory into your path could create
problem like.. I can have 'ls' command written in current directory to delete all the files

Where is kernel located in unix?


When Unix is running, the kernel has been loaded into the memory. The kernel file is located in
/boot, name vmlinux, usually followed by the version.

How to find some particular lines in unix Vi editor which starts with a particular word and
end with another particular word?? For ex - There are 10 lines in the editor and only 4 lines
start with the word APPLE and end with the word MANGO.Now how to find out these
particular lines in Unix?
You can try this cmd
syntax
esc + ?word (Press 'escape' key, type word-to-find)
esc+?APPLE [*] MANGO
'esc` then :/word-to-find then `enter`

how to delete cron tab entries of a perticular ID?


first you can do crontab -l to list down the entries and then compare it with currently executing
Process - check the name or path from where it's getting executed.
Crontab -r (username) removes all the entries of that user.
Explain Memory Partitioning, Paging, Segmentation.
PAGING: Paging memory allocation algorithms divide computer memory into small partitions, and
allocates memory using a page as the smallest building block.
SEGMENTAION: Segmentation means that a part or parts of the memory will be sealed off from
the currently running process, through the use of hardware registers. If the data that is about to
be read or written to is outside the permitted address space of that process, a segmentation fault
will result.

What is kernel? What is the difference between kernel and microkernel? What is the
difference between unix and Linux? What is relational database,hierarchal database. and
network database? their difference?
1) kernel: The kernel is the part of the Operating System(OS) that interacts directly with the
hardware of computer ,through device drivers that are built into the kernel. It provides set of
services that can be used by programs,insulating these programs from the underlying hardware.
Major functions of kernel are:
1. to manage computer memory
2.to control acces to the computer
3.to maintain file system
4.to handle interrupts
5.to handel errors
6.to perform input and output services(which allows computers to interact with terminals,storage
devices and printers) and
7.to allocate the resources of the computer(such as CPU and input/output devices) among users.
2) micro_kernel: A micro-kernel is a minimal operating system that performs only the essential
functions of an operating system. All other operating system functions are performed by system
processes.

Difference between UNIX and Linux:


That's a very broad question and could be answered any number of ways. Probably the simplest
answer is that from a technical point of view there are no major differences. Most people aren't
satisfied with believing that Linux and UNIX are very similar, though. Here's a list of the most
obvious remaining differences.
Origin: UNIX originated in the laboratories of universities and large corporations, as an initiative
within the context of those organisations. Linux was begun by a university student (Linus
Torvalds) without any initial support from any large organisation. Linux also began as in mimickry
of other well-known UNIX-like implementations, whereas the initial UNIX implementations were
original research. Most commercial UNIX versions are also derived from that early research.
Service Model: Most UNIX versions operate on the basis that you can buy help (support and
service contracts). Although such things are increasingly available to Linux technologists,
traditional arrangements consist of providing your own help, with the assistance of a community
of like-minded people. Linux is big, and access to communities is more important than, say, it is
for IBM mainframes.
Equipment: Although Linux runs on many kinds of equipment, it is best known for its support of
commodity IBM-Intel PC-based hardware. Most of the more popular UNIX flavours focus on high-
performance hardware, usually of a proprietory nature, or using high-end standard computing
architectures, like SPARC. With ever-increasing gains in PC hardware, like Serial-ATA, this
distinction is not as large as it used to be, especially for low performance uses, like desktops.
Licensing: Linux follows the Free Software Foundation's radical licensing model, which provides
a great deal of liberty to those that interact with Linux technology. UNIX versions provided by
other vendors have profit strategies embedded in them. People who offer Linux services might
have a profit strategy, but Linux itself doesn't. This means that vendor lock-in is less of an issue
with Linux than it is with other UNIX offerings. It also means that organisations big enough to
have a center of computing competancy always have the choice of "doing it themselves."
Honesty: Linux and related software is extremely visible. You can find out about flaws before you
commit to the technology rather than afterwards. Because of this, a version number in Linux is a
more relable indicator of the quality of the software than in UNIX. For example, most Linux
software spends a long time being version 0 (zero) before it ever qualifies for the label "version
1." In terms of quality, performance and feature set, there's little to separate Linux from the other
UNIXes. Linux has yet to provide genuine real-time scheduling, which some other UNIX versions

do well. Unix was developed using ‘C’ Language. Unix was the foundation on which Linux was
built. Unix has Character based environment while Linux has Graphical as well as Character
based environment. Unix has less numbers of utilities & Features as compare to Linux.Ex:
Number of shells and editors available in Linux is more than Unix.

Explain Stickybit?
The ‘Sticky Bit’ is a permission bit that can be set on either a file or a directory.
If it is set on a file, then that file will remain in memory after execution, thus ’sticking’ in memory.
This is useful when running a multi-user program (such as a bulletin board system that I ran
once) to make the program execute faster for the next user. This was a common programming
tactic earlier in the history of computer programming when speed and disk space were at a
premium.
If the sticky bit is set on a directory, only the owner of files in that directory will be able to modify
or delete files in that directory - even if the permissions set on those files would otherwise allow it.
It executes from user and behaves as it executing from the root.

What is Semaphore?
A data object that represents the right to use a limited resource, used for synchronization and
communication between asynchronous processes.
A semaphore is a type of Interprocess communication resource used for synchronization and
mutual exclusion between any two asynchronous processes.

Explain the unix file system?


Basically there are 4 diiferent types of file systems in unix, they are as follows
1.Device file
2.Directory file.
3.FIFO
4.Regular file

Solaris:-Three types file system


a)Disk base file system
ufs(unix file system),HSFS(High sierra file system),PCFS,UFS(Universal file system)
b)NFS(Network file system)
c)Pseduo or vartual file system
Saapfs,tmpfs,procfs,etc

There are three file system in UNIX as below:-


1. Ordinary File System: contains only data
2. Directory File System: contains other files and directoriesÂ
3. Device File System: represents all hardware devices.

What is the command to find all of the files which have been accessed within the last one
month?
find / -mtime -30 –print
find / -atime -30

What is the use of stat()?


#include <sys/types.h>
#include <sys/stat.h>
int stat(const char *path, struct stat *buf);
The stat() function obtains information about the named file and writes it to the area pointed to by
the buf argument. The path argument points to a pathname naming a file. Read, write or execute
permission of the named file is not required, but all directories listed in the pathname leading to
the file must be searchable. An implementation that provides additional or alternate file access
control mechanisms may, under implementation-dependent conditions,cause stat() to fail.

What is inter-process communication facility?


IPCs are meant for communicating between processes. They are

1. PIPE
2. NAMED PIPE(FIFO)
3. Message Queue
4. Shared memory
5. Semaphore
6. Sockets

Explain difference between IPC mechanisms


ipc mechanisms are mianly 5 types
1. pipes: it is related data only send from one pipe output is giving to another pipe input
to share resources pipe are used
drawback: it is only related process only communicated
2.message queues: message queues are un related process are also communicate with
message queues
drawback:user dont know which process curently works
3.shared memory: memory shared in distributed systems some memory wants to share some
files that time it is use full
4.semaphores: semaphore is integer type and in semaphore resources give coding like negetive
value means process are wants to use perticular resource waiting only
and 0 means no process is waiting
and 1 means one resource is free
5.sockets: sockets also ipc it is comunicate clients and server with socket system calls
connection oriented and connection less also

What are the differences between Shared and Dynamic libraries.


Shared libraries are loaded into memory before compilation, during parsing whereas dynamic
libraries are loaded during compilation time itself.
There are two ways in which a library is shared. Static and dynamic
In statically linked library the code of library is referenced at compile time and the result
executable will be bigger.
I dynamically linked libraries the code of library is referenced at run time and resulting executable
will be smaller. But drwaback is that at run time this will need the library to reference the library
related symbols.
system allow us to create and use two kinds of libraries - static libraries and shared (or dynamic)
libraries.shared and dynamic libraries are one and the same. the object files from the
dynamic(shared ) library are not inserted into the executable file unlike static lib...

What is INODE?
The UNIX disk object that represents the existence of a file. The inode records owner and group
IDs, Fstype, Date & time last access, last modification, n/o links, size of file, addresses of blocks
where the file is physically present and permissions
The inode is the focus of all file activity in the file system. There is a unique inode allocated for
each active file, each current directory, each mounted-on file, text file, and the root. An inode is
"named" by its device/i-number pair.
You can check the inode number of a file by typing ls -li
To add to the definition, when you create a hard link, it is actually another file gets created with
the same inode number. so in a way there is only one inode number which is associated with two
file names having diffrent locations on the disk but acutually refering to the same file. In this case
when you call a delete (rm) on one of hte files you are actually not deleting the file, indeed you
are deleting a reference to the file.
A unique number associated with each filename. This number is used to look up an entry in the
inode table which gives information on the type, size, and location of the file and the userid of the
owner of the file.

How would you print just the 25th line in a file (smallest possible script please)?
sed -n '25p' filename.txt
tail +25 file| head -1
cat -n filename | grep '25'

How do you search the string for vowel's occurrence and number of occurrences of each
vowel
cat filename|tr -d
'eioubcdfghjklmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890()~`!@#$%^&*"()
_+{}|:"<>?,./;][=-/n ' |grep a|tr -d '|wc –m

How to compare floating point number in shell script.


a1=10.50
b1=10.01
if [ $a1 -gt $b1 ]| bc
then
echo "greater"
else
echo "lesser"
fi

Write a shell script to identify the given string is palindrome or not?


this is for strings
#!/bin/sh
echo "enter a string"
read str
var1=`echo $str|rev`
if [ $var1 != $str ] ; then
echo "no pali"
else
echo "pali"
if

//this is for numbers


#!/bin/sh
echo "Enter a number to find for palindrome"
read num1
num=$num1
i=0
while [ $num -gt 0 ]
do
i=`expr $i * 10 + $num % 10`
num=`expr $num / 10`
done
if [ $i -eq $num1 ] ; then
echo "$num1 is a palindrome"
else
echo "$num1 is not a palindrome"
fi
Using Bourne shell : if you enter A B C D E F G.......................n after the command,
how will you write a programme to reverse these positional parameters?
$ echo "$@" | rev

Please make me clear if i am wrong.


=$#
while(($i>=0))
do
echo $i
((i=$i-1))
done

how to delete a word from a file using shell script.


sed -e 's/word//g' filename

If you have a string "one two three", Which shell command would you use to extract the
strings?
echo $string | cut -d" " -f1
echo $string | cut -d" " -f2
echo $string | cut -d" " -f3
echo "one two three" | cut -d" " -f 1,2,3
or
echo "one two three" | awk '{print $1 $2 $3}'
cut , awk, sed and others are not "SHELL" commands. One way could be with bash: string="one
two three"tab=($string)$ echo ${tab[0]}one$ echo ${tab[1]}two$ echo ${tab[2]}threehttp://www.big-
up.org

How do you read arguments in a shell program - $1, $2 ?


#!/bin/sh
for i in $*
do
echo $i
done
On executig the above script with any number of command-line arguments it will display all the
parametsrs.
Shell script accepts parameters in following format...
$1 : first
$2 : second....so on upto
$9 : 9th param
whereas $0 : gives script/function name
If your script has more than 9 params then accept in following way...
${12} : 12th param
${18} : 18th param

How do you schedule a command to run at 4:00 every morning?


by using cron job
Schedule the Job using crontab..From the command prompt perform a "man" on crontab and
then type in crontab -e to create a new "job"
Step 1. Set environemen variable EDITOR=vi if not set
Step 2. Give command crontab -e
Step 3. Add following entry at the end
0 4 * * * <Your command to run at 4:00 am morning>
1. There are two ways to schedule a script to run exactly at 4:00 AM every morning
a: CRONTAB
b. AT (at command executes only once)
Crontab format
* * * * * <command>
<minute> <hour> <date> <month> <day_of_the_week> command
<0-59> <0-23> <1-31> <1-12> <0-7> command

What is use of "cut" command ?Give some examples. Can we use "awk" or "sed" instead
of "cut" ? If yes then give some examples?
This utility is use to cut out columns from a table or fields from each line of a file.
cut can be used as a filter.
Either the -b, -c, or -f option must be specified.
-b list
The list following -b specifies byte positions (for instance, -b1-72 would pass the first 72 bytes of
each line). When -b and -n are used together, list is adjusted so that no multi-byte character is
split.
-c list
The list following -c specifies character positions (for instance, -c1-72 would pass the first 72
characters of each line).
-d delim
The character following -d is the field delimiter (-f option only). Default is tab. Space or other
characters with special meaning to the shell must be quoted. delim can be a multi-byte character.
Cut - Utility used to cut/Strip out the required data/text from the source.
Cut can be used in three modes,
Stripping by Character
cut -c 1-3
STriping by Byte length
cut -b -1-72
Stripping by delimiter and fields.
cut -d "|" -f1
where
-d "|" -> Deleimter used in input text to seperate columns
-f1 -> Field/Column number
while processing Huge input files, Cut's perfomance is far better than awk
Cut is a powerful command in Unix, Cutting fields we can use the command , for example we
would like to extraxct first 3 col
cut -c1-3 sample (Sample is a file name)
To extract first and 3rd col
cut -d;-f1,-f3 sample
CUT is used to get the specific portion(column) of information from a files separated by a specific
charecter(ex: CSV file)

ex: more /etc/passwd|cut -d":" -f1


The above command is used to list the user accounts on the server.
2. AWK
ex: ls -al|awk '{print $9}'
The above command is used to get the list of filenames in the current directory. Here the fields
are need not be seperated by a specific charecter.
3. SED is similar to GREP command.
The cut command cuts bytes, characters, or fields from each line of a file and writes these bytes,
characters, or fields to standard output. If you do not specify the File parameter, the cut command
reads standard input.
To display fields using a blank separated list, enter:
cut -f "1 2 3" -d : /etc/passwd
The cut command produces:
su:*:0
daemon:*:1
bin:*:2
sys:*:3
adm:*:4
pierre:*:200
joan:*:202

How to find see the file which is created today,s date with time after 10 a.m to 5 p.m?
find . -atime 0 -type f -exec ls -ltr {} ; | grep "`date +%b %d`"
This command will show the files which are created today. But for ur second part of the
quesiton i needto analyse more,
Explanation:
find . -atime 0 -type f -exec ls -ltr {}
This will list the files where are accessed and created today.
grep "`date +%b %d`"
This part of the command will filter out unwanted files which were not created today.
set -u -a
rm -f out2
find $PWD -atime 0 -type f -exec ls -ltr {} ; | grep "`date '+%b %d'`" | tr -s " " | tr -d ":" > out2
echo "-------Files Modified Today--------"
cat out2 | while read line
do
timechk=`echo $line | cut -d " " -f8`
filename=`echo $line | cut -d " " -f9`
if [ $timechk -gt 1000 -a $timechk -lt 1700 ]
then
echo $filename
fi
done
echo "-----------------------------------"

What is the difference between a 'thread' and a 'process'?


• Process is a program in execution whereas thread is a separate path of execution in
a program.
• Process & Thread share almost all data structure except (thread has it's own register
& stack area )
• Process is a program under execution, but thread is a light weight process which has
seperate way of execution. Threads are part of process. Single process can contain
number of threads at a time.
• Thread is the part of the process when we execute a programm and the process is
created when execute a program.
• A process is a collection of virtual memory space, code, data, and system resources.
A thread is code that is to be serially executed within a process. A processor
executes threads, not processes, so each application has at least one process, and a
process always has at least one thread of execution, known as the primary thread. A
process can have multiple threads in addition to the primary thread
• Thread – is stream of executable code within process. They are light weight process.
• All thread with in a process share process instruction,code & data segment,open file
descriptor,signal handler,userID and GroupID.
• Thread has its own set of register including program counter,stack pointer

How will you list only the empty lines in a file (using grep)?
grep "^$" filename.txt
grep -c "^$" filename.txt
grep "^[ ]*$" filename.txt
In character set (between [ and ] one space and tab is given)
this command will gives all the blank line including those having space and tabs (if pressed)only
How would you get the character positions 10-20 from a text file?
cat filename.txt | cut -c 10-20
cut -c10-20 <filename.txt>

When you login to a c shell, which script would be run first? (before the terminal is ready
for the user)
.profile file will execute first when a user logs in.
or C shell , first /etc/.login script is run & after that
~/.login is run & then ~/.cshrc is run.

What does command "kill -9" does ?


it will kill the PID(process id)

What are the commands to make a file hidden and to delete all hidden files in the folder?
Rename the file so that it starts with (.)
For example if you have a file called file.txt just rename it to .file.txt
mv file.txt .file.txt

How to terminate a process which is running and the specialty on command kill 0?
With the help of kill command we can terminate the process.
Syntax: kill pid
Kill 0 - kills all processes in your system except the login shell.
KILL <PID> : Kills the process with specific ProcessID
KILL -9 <PID> : Kills a stubburn process which can't killed using KILL command
KILL 0 : Kills all the processes and some times this may result in system crash also causing
heavy core dump
Kill -9 <proc. id>is used to killl a process and all its child processes
Child processes will not be killed with kill -9 command.

what is the command to list files from directory in decreasing order of their file size.
l -rt|sort -knr5
Here ll -rt list the files along with permission, owner, group, etc...
sort will sort the output of ll -rt according to 5th field which is the file size.
Hence the output of list will be sorted according to the file size and it will be listed.

How many prompts are available in a UNIX system?


Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).
Unix/ Linux Supports four Prompts PS1, PS2, PS3, PS4
PS1 Prompt used as the normal system promptPS2 Prompt used when the shell expects more
inputPS3 Prompt used when you have root authority

Bash supports 4 prompts:


PS1 - the default prompt
PS2 - for multi-line input
PS3 - printed for the select command
PS4 - printed before output if set -x is set
The first two are common to the Bourne shell (and ksh). The last two are only for Bash.
csh, however, uses a completely different system. Set the "prompt" variable.

Which of the following commands is not a filter?(a)man , (b) cat , (c) pg , (d) head?
Ans: man pg cat
A filter is a program which can receive a flow of data from std input, process (or filter) it and
send the result to the std output.
What is difference between Hard and Soft mount?
Hardmount in Unix is the same as the normal filesystem mount used mainly for mounting local
filesysytems.Once a filesystem is hard mounted you should use umount command to unmount
it.It remains mounted till you umount it.
Soft mount on the other hand allows automatic unmounting if the filesystem is idle for a specified
timeout period. It is mainly used for network filesystems like NFS It can be configured using
Autofs and the network filesystem can be soft mounted.

Example
I have a file with the following info as comma separated. It shows username, id number and what
subjects they are enrolled in. The subjects are separated by colons.
UserName,ID,Subject
jsmith,235456939,MATH29879:PHYS45979
jdoe,750378929,ENGL36899:JAPN92576

I want it to have one username with one course per line. So that it would look like:
jsmith,235456939,MATH29879
jsmith,235456939,PHYS45979
jdoe,750378929,ENGL36899
jdoe,750378929,JAPN92576
Does anyone have any ideas?

Answer
1) Say your file name is "r1" having following data

STUDENT1,ID1,SUB11
STUDENT2,ID2,SUB21:SUB22
STUDENT3,ID3,SUB31:SUB32:SUB33
STUDENT4,ID4,SUB41:SUB42:SUB44

2)Now write following in a new file "prg.awk"

{FS=","}
{NAME=$1;ID=$2;SUBJECT=$3}
{split(SUBJECT,SUB,":")
{printf "%s,%s,%sn",NAME,ID,SUB[1]}
{if(SUB[2]!=NULL){printf "%s,%s,%sn",NAME,ID,SUB[2]}
{if(SUB[3]!=NULL){printf "%s,%s,%sn",NAME,ID,SUB[3]}
{if(SUB[4]!=NULL){printf "%s,%s,%sn",NAME,ID,SUB[4]}
{if(SUB[5]!=NULL){printf "%s,%s,%sn",NAME,ID,SUB[5]}

3)Make this file as executable, say chmod +x prg.awk

4)Now write the following command

awk -f prg.awk r1

You can add more line with SUB[#] depending of number of subjects
Sorry i forgot to add a closing curly brace } at the end of prg.awk
Without which the program will not work

OR Script Starts here

### Usage : sh format.sh inputFile.txt


if [ $# -ne 1 ] ;
then
echo "Usage : sh format.sh inputFile.txt";
exit 1;
fi
FNAME=$1
CONTENT=`cat $FNAME`;

for LINE in $CONTENT


do
NAME=`echo $LINE | awk -F, '{print $1}'`;
ID=`echo $LINE | awk -F, '{print $2}'`;
SUBJECTS=`echo $LINE | awk -F, '{print $3}' | sed 's/:/ /g'`;
for SUBS in $SUBJECTS
do
echo "$NAME,$ID,$SUBS";
done
done

Script Ends with that done

Create it as script with name like format.sh and pass your file as argument.
it will output the data in your desired format

$ cat input.file
jsmith,235456939,MATH29879:PHYS45979
jdoe,750378929,ENGL36899:JAPN92576

$ sed -e 's/:[A-Z]*[1-9]*//g' input.file>output.file

$ cat output.file
jsmith,235456939,MATH29879
jdoe,750378929,ENGL36899
use below command:

$ cat t.txt
jsmith,235456939,MATH29879:PHYS45979
jdoe,750378929,ENGL36899:JAPN92576

$ cat t.txt|sed "s/:/,/g"|awk -F"," '{OFS=","; print $1,$2,$3;print $1,$2,$4}'


jsmith,235456939,MATH29879
jsmith,235456939,PHYS45979
jdoe,750378929,ENGL36899
jdoe,750378929,JAPN92576

What is the difference between grep and find commands?a)provides information on help
b)grep searches in a file whereas find searches for files and directories.
c)both a) and b)
d) none of the above

Grep is used to find strings in a file.


Find is used to find a file in a directory or to find directory in the list of directories.

Write command to delete all the files from a directory which have been created after a
specified time.
Say you want to delete some files ends with data which are 2 days old.

for file in `find . -follow -type f -name "*data" -mtime +2`


do
rm $file
done

How to switch to a super user status to gain privileges?


Use ‘su’ command. The system asks for password and when valid entry is made the user gains
super user (admin) privileges.
"su" is the command to switch to a super user status (commonly known as root user) from a user
shell.
After that it will ask for password of root.then you are super user.
This command does not load the shell settings for a typical super user that login from a login
screen. Therefore, environment variables/settings remained the same as that of the previous user
shell.
To load root user environment settings with a super user status from a user shell, use "su -"

How do you restore deleted files in unix


After deleting the file forcibly, there is noway you can get this on your own(no roolback as such).
But as its been a tradition of taking backup of certain file systems daily and fortunately if your file
is part of one of those file systems which have been backed up, you can ask unix people to
restore the file (file system).

Write a shell script to list only the hidden files in the current directories?
ls -A | grep ^[.] Works on Linux
ls -a | grep ^[.]
ls -la | grep -v ^d | awk {'print $9'} | grep ^[.]

What is the o/p of following command $a =*, echo $a, echo "$a"?
command $a =*, variable 'a' will have all the files and directories in the current location.. simply
the result of "ls".
echo $a - this will give the list of files and directories
echo "$a" - this wil show value assinged to a.. ie., *

Which of the following is allowed in an arithmetic involving expr instruction. [],{},()? If


values "hi", "Hello","Bye","Good Bye" are supplied to the following statement what will be
the o/p read n1,n2 , echo $n1 $n2?
How do you know that how many commands can be stored in the buffer in one session?
type "env" command on the prompt and check HISTORY or BUFFER or HISTSIZE value

What are shell variables?


Shell variables are special variables, a name-value pair created and maintained by the shell.
Example: PATH, HOME, MAIL and TERM
shell variables are system environment variables.they include TERM,SHELL, MAIL
the output of the shell variable we can see by typing the command
$>echo $TERM
ansi
at the prompt.
There are variable shell variable which would fix the environment once the user logs into OS.
One can find shell variables by issuing "env"
Example shell variables are PATH, TERM, HOME, SHELL etc...
One can define his own shell variables and enter them in "/etc/bashrc" file so that they will take
into effect whenever they log into OS.
Is it possible to create new a file system in UNIX?
Yes, ‘mkfs’ is used to create a new file system.
mkfs -t filesystem device name.
for e.g
mkfs -f ext3 /dev/hda2

How will u list the contents of parent directory from the current directory?
ls -l <directory path>

What are the default system wide permissions for a file and directory?
Directory - 777 - rwxrwxrwx
File - - 055 - ---r_x r_x

What is the default umask value? 022

A user is not able to change the permission , What can it happen?


If he is not the member or owner it will happen

What's the difference between ls -F , ls -p?


ls - F - It will shows whether it is a file or directory, to identify the file type
ls - P - Displays the links directly rather than the object that the link references.

If a file permission are 000, can the superuser still read and write to that file.?
No, he will not be able to read or write, Inorder to do that, he needs to change the
permissions.

What's the command to remove the files without write permission?


rm -fr <filename>

How will u make sure that no one can see the files which u had created?
Create the file starting with .(DOT) It will be hidden. or example cat > .sharvan

How will u change the permissions of a directory recursively?


Use the chmod with -R

What will the following command do?


$ echo * - It is similar to 'ls' command and displays all the files in the current directory.

Write a command to kill the last background job?


Kill $!
The system variable $! stores the PID of the last background job.
The other method is first find the PID using the ps command, then use kill command to do the job.

Unix command to concatenate (attach) two strings?


For concatenating two string we use cat command.
Ex:- cat str1 str2
Variable1="Open"
Variable2="Systems"
Variable3=$Variable1$Variable2
echo $Variable3
Output OpenSystems
Name the system calls used for process management
System Calls for process control * fork() * wait() * execl(), execlp(), execv(), execvp() * exit() *
signal(sig, handler) * kill(sig, pid)
Extensively used one are: ps –eaf, kill, fork
What is the difference between soft link and hard link.
Hard Links :
1. All Links have same inode number.
2.ls -l command shows all the links with the link column(Second) shows No. of links.
3. Links have actual file contents
4.Removing any link ,just reduces the link count , but doesn't affect other links.
Soft Links(Symbolic Links) :
1.Links have different inode numbers.
2. ls -l command shows all links with second column value 1 and the link points to original file.
3. Link has the path for original file and not the contents.
4.Removing soft link doesn't affect anything but removing original file ,the link becomes "dangling"
link which points to nonexistant file.

Soft link:-This is a Symbolic link between files.The actual file or directory , must be residing at
any available partitions of the harddisk, Soft Link is just a "shortcut" (in windows terms) or "link"
created with a new file name at the working directory or at current working partition of hard disk.
Even when you don't require it, you can confidently delete this "soft link" as it doesn't remove the
actual file or directory. The reason is, the actual file or diretcory's inode is different from the
"softlink" created file's inode, in any unix system.Hard link:-It is the replica of the actual file or
directory , which must be residing at any available partitions. This is a duplicate file copy of it's
orginal , which can be created at current , working partition.When we remove or delete , this
hardlink, it removes the original file or directory too.The reson is , they share the same inode , in
any unix file system.With regards,Siddhun.M.Karthik
softlink is useful when you want to refer files from other computer /filesystem through NFS .hard
link doesn't allow this.

Basic difference btw soft link and hard link.


Soft link can span across file system Hard link cannot span across file system
Soft link have different inod numbers ( ls -li) Hard link have same inod number for all files
Soft link can link directories and files Hard link can only link files not directories
You can create non existing files with the soft link Hardware link fails if the source files dont
exists.
If you remove the source files, soft link will not work . Remove the source files in hard link , still
data will be available if its a hard link.
Usage : ln -s source file target file ( soft link)
Usage :ln source file target file ( hard link)
In hard link .... the original file will not be deleted when you delete the hard link it ll be deleted only
when the link count becomes zero

Construct pipes to execute the following jobs?


1. Output of who should be displayed on the screen with value of total number of users who have
logged in displayed at the bottom of the list.
2. Output of ls should be displayed on the screen and from this output the lines containing the
word ‘poem’ should be counted and the count should be stored in a file.
3. Contents of file1 and file2 should be displayed on the screen and this output should be
appended in a file .
From output of ls the lines containing ‘poem’ should be displayed on the screen along with the
count.
4. Name of cities should be accepted from the keyboard . This list should be combined with the
list present in a file. This combined list should be sorted and the sorted list should be stored in a
file ‘newcity’.
5. All files present in a directory dir1 should be deleted any error while deleting should be stored
in a file ‘errorlog’.

1.who | tee /dev/pts/4 | cut -d " " -f 1 | uniq | echo "no of users logged in are `wc -l`"
who - displays all the logged in users tee - pass the who output to terminal output /dev/pts/4 and
also to cut command.
where /dev/pts/4 is the current terminal. use tty to get your current terminal
cut -d " " -f1 will cut the first field of who o/p which is login name
uniq command is used to merge duplicate logins to single entry. This might be in some cases a
single user might have logged in from different terminals and in such case they should not be
counted as separate users.
wc -l give total number of line which is here is the total users logged in.
eg o/p: root pts/3 Nov 14 14:30 root pts/4 Nov 21 12:25 no of users logged in are 1
2. ls | tee /dev/pts/4 | grep -c "poem" > count | cat count
3. sort -m fil1 file2 | tee /dev/pts/4 | sort -o outputfile
4. sort - file1 -o newcity enter extra string from keyboard and press Ctrl+d key combination
to finish the input
5. rm -rf /dir 2>errorlog where 2 denotes "standard error" which is here redirected to
errorlog file instead of user terminal

What is the difference between cat and more command?


Cat displays file contents. If the file is large the contents scroll off the screen before we view it. So
command 'more' is like a pager which displays the contents page by page.
In Unix, cat command is used to display the contents on to the screen - $cat filename
more command is used to diaplay a file with pausing. - $more filename

The cut command cuts bytes, characters, or fields from each line of a file and writes these bytes,
characters, or fields to standard output. If you do not specify the File parameter, the cut command
reads standard input.The more command reads files and displays the text one screen at a time.
The command pauses after each screen and prints the word More at the bottom of the screen. If
you then press a carriage return, the more command displays an additional line. If you press the
space bar, the more command displays another full screen of text. Note: On some terminal
models, the more command clears the screen, instead of scrolling.

Name the data structure used to maintain file identification?


The data structure that is used to maintain the In-Core Inode Information is "Inode Table". This
table (logical representation) has the following information abt the file:-
- type of the file
- permissions on the link
- Owner Id
- Group Id
- File Size
- Array of 13 pointers to a file or another entry in the inode table.
Besides these, the UNIX system maintains 2 other data structures namely -
User File Descriptor Table - A per Process table maintains information of open files by single
process
PK - PID , FileDescriptor
2. File Table - A Global Table that maintains the information of all the open files.
PK – FileDescriptor

Explain kill() and its possible return values?


kill is a system call that allows a user process to send signals to another process.generally its the
kernel that sends signals to processes.
There are four possible results from this call:
1.‘kill()’ returns 0. This implies that a process exists with the given PID, and the system would
allow you to send signals to it. It is system-dependent whether the process could be a zombie.
2.‘kill()’ returns -1, ‘errno == ESRCH’ either no process exists with the given PID, or security
enhancements are causing the system to deny its existence. (On some systems, the process
could be a zombie.)
3.‘kill()’ returns -1, ‘errno == EPERM’ the system would not allow you to kill the specified
process. This means that either the process exists (again, it could be a zombie) or draconian
security enhancements are present (e.g. your process is not allowed to send signals to
*anybody*).
4.‘kill()’ returns -1, with some other value of ‘errno’ you are in trouble! The most-used
technique is to assume that success or failure with ‘EPERM’ implies that the process exists, and
any other error implies that it doesn't.
An alternative exists, if you are writing specifically for a system (or all those systems) that provide
a ‘/proc’ filesystem: checking for the existence of ‘/proc/PID’ may work.

What is difference between lilo and stub?


STUB is A temporary implementaion of part of a program for debugging purposes.
LILO (LInux LOader) is a boot loader for Linux.

Is it possible to count number char, line in a file; if so, How?


Yes,It is possible to count the words,lines,characters in a file..
wc-stands for word count.
$wc -c filename -> for characters
$wc -l filename ->for lines
$wc -w filename ->for words

What difference between cmp and diff commands?


cmp - Compares two files byte by byte and displays the first mismatch
diff - tells the changes to be made to make the files identical
cmp <filename1> <filename2> gives the 1st byteno and lineno of file1 which is to be changed to
make filename1 identical to filename2.
diff gives the text of filename2 which is different from filename1.we can use directory name in
diff, but not in cmp

How does the kernel differentiate device files and ordinary files?
Kernel checks 'type' field in the file's inode structure.
device filles are of 2 types --- character device file and block device file
type field in the file's inode structure
b--- block device file
c--- character device file

What are the difference between Daemons in Unix and service processes in Windows?
both are same. daemons are the background processes in unix.
similarly background processes in windows are called as service agents or service processes.

Define Demand Paging, Page fault interrupt, and Trashing?


Demand Paging: Demand paging is the paging policy that a page is not read into memory until it
is requested, that is, until there is a page fault on the page.
Page fault interrupt: A page fault interrupt occurs when a memory reference is made to a page
that is not in memory.
The present bit in the page table entry will be found to be off by the virtual memory hardware and
it will signal an interrupt.
Trashing: The problem of many page faults occurring in a short time, called “page thrashing,”
Unix Vs. Windows OS
An operating system (OS) is a program that allows you to interact with the computer -- all of the
software and hardware on your computer. How?
Basically, there are two ways.
 With a command-line operating system (e.g., DOS), you type a text command and the
computer responds according to that command.
 With a graphical user interface (GUI) operating system (e.g., Windows), you interact with
the computer through a graphical interface with pictures and buttons by using the mouse
and keyboard.
With Unix you have in general the option of using either command-lines (more control and
flexibility) or GUIs (easier).

Unix and Windows: Two Major Classes of Operating Systems


And they have a competitive history and future. Unix has been in use for more than three
decades. Originally it rose from the ashes of a failed attempt in the early 1960s to develop a
reliable timesharing operating system. A few survivors from Bell Labs did not give up and
developed a system that provided a work environment described as "of unusual simplicity, power,
and elegance".
Since the 1980's Unix's main competitor Windows has gained popularity due to the increasing
power of micro-computers with Intel-compatible processors. Windows, at the time, was the only
major OS designed for this type of processors. In recent years, however, a new version of Unix
called Linux, also specifically developed for micro-computers, has emerged. It can be obtained for
free and is therefore a lucrative choice for individuals and businesses.
On the server front, Unix has been closing in on Microsoft’s market share. In 1999, Linux scooted
past Novell's Netware to become the No. 2 server operating system behind Windows NT. In 2001
the market share for the Linux operating system was 25 percent; other Unix flavors 12 percent.
On the client front, Microsoft is currently dominating the operating system market with over 90%
market share.
Because of Microsoft’s aggressive marketing practices, millions of users who have no idea what
an operating system is have been using Windows operating systems given to them when they
purchased their PCs. Many others are not aware that there are operating systems other than
Windows. But you are here reading an article about operating systems, which probably means
that you are trying to make conscious OS decisions for home use or for your organizations. In
that case, you should at least give Linux/Unix your consideration, especially if the following is
relevant in your environment.

Advantages of Unix
- Unix is more flexible and can be installed on many different types of machines, including
main-frame computers, supercomputers and micro-computers.
- Unix is more stable and does not go down as often as Windows does, therefore requires
less administration and maintenance.
- Unix has greater built-in security and permissions features than Windows.
- Unix possesses much greater processing power than Windows.
- Unix is the leader in serving the Web. About 90% of the Internet relies on Unix operating
systems running Apache, the world's most widely used Web server.
- Software upgrades from Microsoft often require the user to purchase new or more
hardware or prerequisite software. That is not the case with Unix.
- The mostly free or inexpensive open-source operating systems, such as Linux and BSD,
with their flexibility and control, are very attractive to (aspiring) computer wizards. Many of
the smartest programmers are developing state-of-the-art software free of charge for the
fast growing "open-source movement”.
- Unix also inspires novel approaches to software design, such as solving problems by
interconnecting simpler tools instead of creating large monolithic application programs.

UNIX versus Windows


- As far as operating systems go, to some it would seem as if UNIX has a clear advantage
over Windows.
- UNIX offers greater flexibility than Windows operating systems;furthermore, it is more
stable and it does not crash as much as much as Windows.
- To some, UNIX is just as easy to use as Windows, offering a GUI interface as well as
command line. But there are users out there that believe UNIX is for only for computer
gurus only, claiming that the fragmentation of the UNIX GUI is its greatest competitive
weakness.
- UNIX is quite a bit more reliable than Windows, and less administration and maintenance
is needed in maintaining a UNIX system. This is a huge cost saver for any organization.
- Rather than employing many individuals to maintain a Windows based system, one part-
time employee would be needed for the upkeep of a typical size UNIX system.
- One key difference between UNIX and Windows is the implementation of multiple users
on one computer. When a user logs onto a UNIX system, a shell process is started to
service their commands. Keeping track of users and their processes, a UNIX operating
system is able to keep track of processes and prevent them from interfering with each
other. This is extremely beneficial when all the processes run on the server, which
demands a greater use of resources - especially with numerous users and sizeable
applications.
- Another main difference between UNIX and Windows is the process hierarchy which
UNIX possesses. When a new process is created by a UNIX application, it becomes a
child of the process that created it. This hierarchy is very important, so there are system
calls for influencing child processes.
- Windows processes on the other hand do not share a hierarchical relationship. Receiving
the process handle and ID of the process it created, the creating process of a Windows
system can maintain or simulate a hierarchical relationship if it is needed. The Windows
operating system ordinarily treats all processes as belonging to the same generation.
- UNIX uses daemons, Windows has service processes. Daemons are processes that are
started when UNIX boots up that provide services to other applications. Daemons
typically do not interact with users. A Windows service is the equivalent to a UNIX
daemon. When a Windows system is booted, a service may be started. This is a long
running application that does not interact with users, so they do not have a user interface.
Services continue running during a logon session and they are controlled by the Windows
Service Control Manager.
- UNIX has a novel approach to designing software. Since UNIX is open-sourced, it
attracts some very intelligent programmers who develop many applications free of
charge. With this in mind, many designers choose to resolve software problems by
creating simpler tools that interconnect rather than creating large application programs. In
contrast, Windows applications are all proprietary and costly.
- With UNIX, each generation extends, rather than replaces the previous like Windows it is
rarely necessary to upgrade - old and new Unix are all compatible. The main reason for
this is the way UNIX is built, which is on a solid theoretical foundation. There are many
advantages to this, for instance, a book written 20 years ago that discusses programming
UNIX can still be used today. Imagine trying to figure out how to run Windows XP with a
Window 3.1 manual - it can't be done.
- One argument to be made about UNIX is its lack of standardization. Some feel there are
too many choices to be made regarding which GUI to use, or which combination of UNIX
hardware and software to support. UNIX operating systems make great high-
performance servers, but for end-users, every application on each arrangement of UNIX
platform requires a different set, and each application has a different user interface.
Microsoft has "the" Windows operating system; there simply isn't one standardized UNIX
operating system, or for that matter, a single standardized UNIX GUI. One could argue
and say this is a downfall for UNIX, but on the other hand, these variations add flavor and
versatility to a solid, reliable operating system.
- In summary, the best way to choose between UNIX and Windows is to determine
organizational needs. If an organization uses mostly Microsoft products, such as Access,
Front Page, or VBScripts, it's probably better to stick with Windows. But, if reliability,
universal compatibility, and stability are a concern, UNIX would probably be the way to
go.

You might also like