0% found this document useful (0 votes)
8 views

Os Lab 1-6 Programs

Uploaded by

bjeshmasri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Os Lab 1-6 Programs

Uploaded by

bjeshmasri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

EXPERIMENT-1

UNIX/LINUX PROGRAMMING
1(a).Study of unix/linux general purpose utility commands:
1. man: view manual pages for UNIX commands

Syntax:- man[-s section ]item

$man cat

2. who: displays the list of users logged presently

Syntax:- who [option]...[file][arg1]

$who

3. cat: concatenate files and show contents to the standard output

Syntax:- cat [option]...[file]

$cat>file1

Hello

4. cd: change directory

Syntax:-cd[option] directory

$cd dir1

5. cp: copy files

Syntax:- cp[option] source destination

$cp file1 file2

6. ps: reports process status

Syntax:- ps[options]

7. ls: list of files and directories.

Syntax:- ls[option] [file]

$ls

8. mv: rename or move files and directories to another location

Syntax:- mv [option] source destination


$mv file1 file2

9. rm: removes files and directories

Syntax:- rm[option]...[file]

$rm file1

10. mkdir: makes new directory

Syntax:- mkdir [option]directory

$mkdir dir1

11. rmdir: removes directory

Syntax:-rmdir [option]directory

$rmdir dir1

12. echo: display a line of text to the standard output

Syntax:-$echo “hello world”

$echo $x

13. more: basic pagination when viewing text files or passing UNIX
commands output.

Syntax:-more [options] [num] [+/pattern] [+linenum]


[file_name]

$more +/reset sample.txt

$more +30 sample.txt

14. date: show current date & time

Syntax:- date [+format]

$date + %d/%m/%y

15. time: shows current time

$time

16. kill: terminates a specified process

Syntax:- kill PID

$ kill 4901
17. history: displays history commands in the current session

Syntax:- history [options]

$history

18. chmod:- change file/directory access permissions

Symbolic mode:-

Syntax: chmod [ugoa][[+-=][mode]]file

 the first optional parameter indicates who- this can be


(u)user,(g)group,(o)others or all(a).
 The second optional parameter indicates the opcode –
this can be for adding (+), removing (-) or assigning(=) a
permissions.
 The third optional parameter indicates the mode – this
can be (r) read,(w) write or (x) execute .
$chmod o-w file1

Numeric mode:-

Syntax: chmod [mode]file

 The mode is a combination of three digits- the first digit


indicates the permission for the user,the second digit for the
group, and the third digit for others.
 Each digit is computed by adding the associated permissions.
Read permissions is ‘4’, write permission is ‘2’ and execute
permission is ‘1’

$chmod 777 file1

19. chown: change file/directory ownership

Syntax:- chown [owner] [file]

$chown user2 file1

20. finger: displays user info if login is known

Syntax: finger username

21. pwd: confirm current directory


Syntax: pwd [option]

$pwd

22. cal: displays calendar

Syntax: cal [[month]year]

$cal 25 2001

23. logout: logs off UNIX

Syntax: logout [options]

$logout

24. shutdown: brings the system down in a secure way.

Syntax: shutdown [options]

$shutdown
(b) Study of vi editor:
 Visual editor for editing programs.
 The ‘vi’ editor is the most popular and classic text editor in the
linux family.
 This editor enables you to edit lines in context with other lines in
the file.
 Below, are some reasons which make it a widely used editor?
 It is available in almost all linux distributions.
 It works the same across different platforms and
distribution.
 It requires very few resources.
 It is more user-friendly than other editors such as the ed or
the ex.
 We can use the vi editor to edit an existing file or to create a new
file form scratch.
 We can also use this editor to just read a text file .
An improved version of the vi editor which is called the VIM has also
been made available now. Here,VIM stands for vi IM proved.

Starting the vi editor:-


To launch the vi editor –open the terminal(CLI) and type

Vi<filename_NEW>or<filename_EXISTING>

And if you specify an existing file, then the editor would open it for you
to edit. Else, you can create a new file.

The following table lists out the basic commands to use the vi editor -

s.no. Command Description


1. Vi filename Creates a new file if it already does not exit,
otherwise open existing file.
2. Vi –R filename Opens an existing file in the read-only mode.

Operation modes:-
To work on vi editor , we need to understand its operation modes.

 Command mode: This mode enables you to perform


administrative tasks such as saving files, executing the commands,
moving the cursor, cutting(yanking) and pasting the lines are
words, as well as finding and replacing. In this mode, whatever
you type is interpreted as a command.
 Insert mode: this mode enables you to insert text into the file.
everything that’s typed in this mode is interpreted as input and
placed in the file.

Vi always starts in the command mode. To enter text, you must be in the
insert mode for which simply type ‘i’. To come out of the insert mode,
press the Esc key, which will take you back to the command mode.

Vi editing commands:-
Note:- you should be in the “command mode” to execute these
commands.

Vi editor is case-sensitive so make sure to type the commands in the


right letter-case, otherwise you will end up making undesirable changes
to the file.

s.no. Command Description


1 i Insert at cursor (goes into insert mode)
2 a Write after cursor (goes into insert mode)
3 A Write at the end of line (goes into insert
mode)
4 Esc Terminare insert mode
5 u Undo last change
6 U Undo all changes to the entire line
7 o Open a new line (goes into insert mode)
8 dd Delete line
9 3dd Delete 3 lines
10 D Delete contents of line after the cursor
11 C Delete contents of a line after the cursor
and insert new text. Press esc key to end
insertion
12 dw Delete word
13 4dw Delete 4 words
14 cw Change word
15 X Delete character at the cursor
16 r Replace character
17 R Overwrite characters from cursor onward
18 s Substitute one character under cursor
continue to insert
19 S Substitute entire line and begin to insert at
the beginning of the line.
20 ~ Change case of individual character

Moving within a file:-


Note:- you need to be in the “command mode” to move within a file.

The default keys for navigation are mentioned below else; you can
also ues the arrow keys on the keyboard.

s.no. Command Description


1. k Move cursor up
2. j Move cursor down
3. h Move cursor left
4. l Move cursor right

Saving and closing the file:-


Note:- you should be in the “command mode” to exit the editor and
save changes to the file.

s.no Commands Description


.
1. shift+zz Save the file and quit
2. :w Save the fie but keep it open
3. :q Quit without saving
4. :wq Save the file and quit

****************************************************
2.Study of bash shell , bourne shell and c
shell in unix/linux operating system:
What is a shell?
A shell is a program that provides an interface between a
user and an operating system(OS) kernel.

An os starts a shell for each user when the user logs in or


opens a terminal or console window.

A kernel is a program that:

 Controls all computer operations.


 Coordinates all executing utilities.
 Ensures that executing utilities do not interfere with
each other or consume all system resources.
 Schedules and manages all system processes.

By interfacing with a kernel, a shell provides a way for a user to


execute utilities and programs.

Types of Shell:-
1. Bourne shell (sh):-
 The bourne shell is one of the original shells, developed for
UNIX computers by Stephen bourne at AT&T Bell labs in
1997.
 It offers features such as input and output redirection, shell
scripting with string and integer variables, and condition
testing and looping.
 Command full-path name is /bin/bash and /sbin/sh.
 Default prompt for a non-root user is $.
 Default prompt for a root user is #.
2. C shell (csh):-
 The c shell was designed to allow users to write shell script
programs using syntax very similar to that of the C
programming language.
 The c shell is a UNIX shell created by Bill Joy.
 The c shell is a command processor typically run in a text
window, allowing the user to type commands.
 Command full-path name is /bin/csh.
 Default prompt for a non-root user is hostname %.
 Default prompt for a root user is hostname #.
3. Bourne Again shell (bash):-
 The default Linux shell.
 Backward – compatible with the original sh UNIX shell.
 Bash is largely compatible with sh and incorporates useful
features from the korn shell ksh and the c shell csh .
 Command full-path name is /bin/bash.
 Default prompt for non-root user is bash-x.xx$. (where x.xx
indicates the shell version number. For example, bash-3.50$)
 Root user default prompt is bash-x.xx#. (where x.xx
indicates the shell version number. For example,
bash- 3.50$#)
3.Study of UNIX/LINUX file
system(tree structure).
UNIX/LINUX file system (tree
structure):
 UNIX file system is a logical method of organizing and
storing large amounts of information in a way that makes it
easy to manage.
 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 filr system.
 A file is a smallest unit in which the information is stored.
 Files in unix system are organized into multi-level hierarchy
structure known as a directory tree. At very top of the file
system is a directory called “root” which is represented by a
“/”. All other files are “descendants” of root.

1. /-root:-
 Every single file and directory starts from the root
directory.
 Only root user has write privilege under this directory.
 Please note that /root is root user’s home directory,
which is not same as /.
2. /bin- User binaries:-
 Contains binary executables.
 Common linux commands you need to use in single –
user modes are locates under this directory.
 Commands used by all users of the system are located
here.
 For example: ps,ls,ping,grep,cp.
3. /sbin- System binaries:-
 Just like /bin, /sbin alos contains binary executables.
 But the linux commands located under this directory arr
used typically by system administrator, for system
maintenance purpose.
 For example: iptables , reboot, fdisk, ifconfig, swapon.

4. /etc-Configuration files:-
 Contains configuration files required by all programs.
 This also contains startup and shutdown shell scripts
used to start/stop individual programs.
 For example:/etc/resolv.conf, /etc/logrotate.conf
5. /dev –Device files:-
 Contains device files.
 These include terminal devices, usb or any device
attached to the system.
 For example:/dev/tty 1, /dev/usbmon0.
6. /proc – Process information:-
 Contains information about system process.
 This is a pseudo filesystem contains information about
running process. For example:/proc/{pid} directory
contains information about the process with that
particular pid.
 This is a virtual file system with text information about
system resources. For example:/proc/uptime.
7. /var –Variable files:-
 Var stands for variable files.
 Content of the fies that are expected to grow can be
found under this directory.
 This includes- system log files(/var/log); packages and
database files(/var/lib); emails(/var/mail); print
queues(/var/spool); lock files(/var/lock); temp files
needed across reboots(/var/tmp);
8. /tmp- temporary files :-
 Directory that contains temporary files created by
system and users.
 Files under this directory are deleted when system is
rebooted.
9. /usr- User programs:-
 Contains binaries, libraries, documentation and source –
code for second level programs.
 /usr/bin contains binary files for user programs. If you
cant find a user binary under /bin, look under /usr/bin.
For example: at, awk, cc, less, scp.
 /usr/sbin contains binary files for system administrators.
If you cant fin a system binary under/sbin, look
under/user/sbin. For example: atd, cron,
sshd, useradd, userdel.
 /usr/lib vontains libraries for /usr/bin and /usr/sbin.
 /usr/local contains users programs that you
install from source. For example, when you
install apache from source, it goes under
/usr/local/apache2.
10./home- Home directories:-
 Home directories for all users to store their personal files.
 For example:/home/john, /home/nikitha.
11./boot- Boot loader files:-
 Contains boot loader related files .
 Kernel initrd, vmlinux, grub files are located under /boot.
 For example: initrd.img-2.6.32-24-
generic, vmlinux- 2.6.32-24-generic.
12./lib- System libraries:-
 Contains library files that supports the
binaries located under/bin and /sbin.
 Library filenames are either id* or lib*.so.*
 For example: id-2.11.1.so, libncurses.so.5.7
13./opt- Optinal add-on application:-
 Opt stands for optinal.
 Contains add-on applications from individual vendors.
 Add-on applications should be
installed under
either/opt/or/opt/sub- directory.
14./mnt- Mount directory:-
 Temporary mount directory where syasdmins
can mount file systems.
15./media- Removable media devices:-
 Temporary mount directory for removable devices.
 For example, /media/cdrom for CD-ROM;
/media/floppy for floppy drives;
/media/cdrecorder for CD writer.
16./srv- Service data:-
 srv stands for service.
 Contains server specific services related data.
 For example, /srv/cvs contains cvs related data.
4.C program to emulate the UNIX ls -l command
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de;
DIR *dr = opendir("osrecord");
if (dr == NULL)
{
printf("Could not open current directory");
return 0;
}
while ((de = readdir(dr)) != NULL)
printf("%s\n",de->d_name);
closedir(dr);
return 0;
}
5.C program that illustrates how to execute two commands
concurrently
with a command pipe. Ex: - ls –l | sort

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
int pfds[2];
char buf[30];
if(pipe(pfds)==-1)
{
perror("pipe failed");
exit(1);
}
if(!fork())
{
close(1);
dup(pfds[1]);
system ("ls -l");
}
else
{
printf("parent reading from pipe \n");
while(read(pfds[0],buf,80))
printf("%s \n" ,buf);
}
}
6.Multiprogramming Memory management Implementation of
fork(),wait(),exec() and exit(),system calls

DESCRIPTION:
FORK():
Fork
system call use for creates a new process, which is called , which runs concurrently with process (which
process called system call fork) and this process is called . After a new child process created, both
processes will execute the next instruction following the fork() system call. A child process uses the same
pc(program counter), same CPU registers, same open files which use in the parent process.
EXEC():
The exec family of functions replaces the current running process with a new process. It can be used to
run a C program by using another C program. It comes under the header file unistd.h. There are many
members in the exec family which are shown below with examples.
·
execvp : Using this command, the created child process does not have to run the same program as the
parent process does. The exec type system calls allow a process to run any program files, which include a
binary executable or a shell script .

Syntax:
int execvp (const char *file, char *const argv[]); file: points to the file name associated with the file being
executed.
argv: is a null terminated array of character pointers.
·
execv : This is very similar to execvp() function in terms of syntax as well. The syntax of execv() is as
shown below:

Syntax:
int execv(const char *path, char *const argv[]);
path: should point to the path of the file being executed.
argv[]: is a null terminated array of character pointers.

execlp and execl : These two also serve the same purpose but the syntax of of them are a bit different
which is as shown below:
Syntax:
int execlp(const char *file, const char *arg,.../* (char *) NULL */);
int execl(const char *path, const char *arg,.../* (char *) NULL */);
·
execvpe and execle :
These two also serve the same purpose but the syntax of them are a bit different from all the above
members of exec family. The synatxes of both of them are shown below :
Syntax:
int execvpe(const char *file, char *const argv[],char *const envp[]);

Syntax:
int execle(const char *path, const char *arg, .../*, (char *) NULL, char * const envp[] */);

WAIT() :
A
call to wait() blocks the calling process until one of its child processes exits or a signal is received. After
child process terminates, parent continues its execution after wait system call instruction.Child process
may terminate due to any of these:
· It calls exit();
· It returns (an int) from main
· It receives a signal (from the OS or another process) whose default action is to terminate.
EXIT():
It terminates the calling process without executing the rest code which is after the exit()
function.
FORK()
PROGRAM:
/* C Program to implement Fork() system calls */

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
if (fork() == 0)
printf("Hello from Child!\n");

else
printf("Hello from Parent!\n");
}
int main()
{
forkexample();
return 0;
}

OUTPUT:

Hello from Child!Hello from Parent!


EXEC():

/* C Program to implement Exec() system calls */


PROGRAM:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int ret = 1;
int status;
pid = fork();
if (pid == -1)
{

printf("can't fork, error occured\n");


exit(EXIT_FAILURE);
}
else if (pid == 0)
{
printf("child process, pid = %u\n",getpid());
exit(0);
}
else{
printf("parent process, pid = %u\n",getppid());
if (waitpid(pid, &status, 0) > 0)
{
if (WIFEXITED(status) && !WEXITSTATUS(status))
printf("program execution successfull\n");
else if (WIFEXITED(status) && WEXITSTATUS(status))
{
if (WEXITSTATUS(status) == 127)
{
printf("execv failed\n");
}
else
printf("program terminated normally,"
" but returned a non-zero status\n");
}
else
printf("program didn't terminate normally\n");
}
else
{
printf("waitpid() failed\n");
}
exit(0);
}
return 0;
}

OUTPUT:

parent process, pid = 11523child process, pid = 14188Program execution successfull


WAIT() :

PROGRAM:

/* C Program to implement Wait() system calls */

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

int main()
{
pid_t cpid;
if (fork()== 0)
exit(0);
else
cpid = wait(NULL);
printf("Parent pid = %d\n", getpid());
printf("Child pid = %d\n", cpid);

return 0;
}

EXIT():

PROGRAM:
/* C Program to implement Exit() system calls */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("START");
exit(0);
printf("End of program");
}

OUTPUT:

START

You might also like