You are on page 1of 21

DSE-II: UNIX Shell Programming

Unit-1: Introduction

UNIX Operating system


• UNIX was developed in 1969 by a group of computer researcher Ken Thompson,
Dennis Ritchie, Brain Kernighan, Douglas Mcllroy, and Joe Ossanna at AT&T
Bell Labs.
• There are various variants of UNIX available in the market. Solaris UNIX, IBM AIX,
HP UNIX and BSD Unix are a few examples. Linux is also a flavour of UNIX which
is freely available.
• Several people can use a UNIX operating system at the same time; hence UNIX is
called a multiuser system.
• A user can also run multiple programs at the same time; hence UNIX is a
multitasking environment.
• The UNIX operating system is written in a high-level language, making it easy to
read, understand, change, and move to other machines.
• It has a simple user interface that has the power to provide the services that users
want. It provides primitives that permit complex programs to be built from simpler
programs.
• It uses a hierarchical file system that allows easy maintenance and efficient
implementation.
• It provides a simple, consistent interface to peripheral devices.
• It hides the machine architecture from the user, making it easier to write programs
that run on different hardware implementations.
• Although the operating system and many of the command programs are written in C,
UNIX systems support other languages, including Fortran, Basic, Pascal, Ada,
Cobol, Lisp, and Prolog.
• The UNIX system can support any language that has a compiler or interpreter and
a system interface that maps user requests for operating system services to the
standard set of requests used on UNIX systems.

1 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Difference between UNIX and Linux (Linux is a UNIX)
UNIX LINUX
1. It is not an open source system, i.e. 1. It is free and open Source software;
Source code is not available to general Source code is available to the
public. general public.
2. UNIX is licensed OS. 2. Linux is free to use.
3. Developed by Ken Thompson, Dennis 3. Developed by Linus Torvalds.
Ritchie and Brain Kernighan. 4. Ubuntu, Fedora, RedHat are some of
4. Solaris, HP UNIX, IBM AIX are some Linux Versions.
UNIX versions.

Difference between UNIX and DOS


DOS UNIX
1. OS is an operating system used in x86- 1. UNIX is a multitasked, multiuser
based computers developed by operating system used in powerful
Microsoft. computers.
2. DOS had released in 1981 2. UNIX OS released in November
3. MS-DOS is a single-process Operating 1971.
System. 3. UNIX is a multitasking Operating
4. DOS is less secure as compared to System.
UNIX. 4. UNIX is more secure.

Differences between UNIX and Windows


UNIX WINDOWS
1. UNIX has very high security system. 1. Windows has low security system.
2. UNIX is a command-based operating 2. Windows is a GUI-based
system. operating system.
3. The file system is arranged in hierarchical 3. The file system is arranged in
manner. parallel manner.
4. UNIX is not user friendly. 4. Windows is a user friendly.
5. Free office Suit is available (such as excel, 5. We need to pay for Ms Office.
PowerPoint and others). 6. Not customizable.
6. Customizable and features can be added.

2 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Features of UNIX
1. Simple design- The architecture of the UNIX is simple and organized.
2. Portability- The code can be changed and compiled on a new machine.
3. UNIX Shell- The user interface of UNIX Shell provides the services that the user wants.
4. Hierarchical file System: - UNIX uses a hierarchical file structure to store information.
5. Multiuser- It allows more than one user to share the computer system at the same time.
6. Multi-Tasking- More than one program can run at a time.
7. Security- It provides high security (System level security and File level security).
8. Pipes and Filters–We can create complex programs from simple programs.
9. Utilities- It has over 250 utility programs for various functions.
10. Machine Independence-The System hides the machine architecture from the user,
making it easier to write application that can run any computer system.
11. Program Facility-It has all necessary techniques like control structure loops and
variables for programming. These Techniques are useful for shell scripting
programming.

UNIX Architecture

[Basic block diagram of a UNIX system]

3 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
The Architecture of the UNIX system is divided into 4 major components. They are: - The
Kernel, The Shell, Commands and Utilities, and Files and Directories.

1. The Kernel
• The kernel is the heart of the operating system.
• It is the interface between Shell and Hardware.
• It performs Low level task like Process Management, Memory Management etc.
2. The Shell
• The Shell is a collection of UNIX commands. The Shell acts as an interface
between the user and the Kernel.
• The Shell is a Command Line Interpreter (CLI) – It translates the commands from
the user and converts it into a language that is understood by the kernel.
• Only one kernel runs on a system, but several shells will be active for each user
who is logged into the system.
• C Shell, Bourne Shell and Korn Shell are the most famous shells which are
available with most of the UNIX variants.

3. 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
third party software. All the commands come along with various options.

4. Files and Directories:


• All the data in UNIX is organized into files. All files are then organized into
directories. These directories are further organized into a tree-like structure called
the file system.

Booting and shutdown process


• In a system where UNIX operating system installed, you simply need to turn on the
system to make it available for service.
• When you turn on the system, it starts booting up and finally it prompts you to log
into the system, which is an activity to log into the system and use it for your day-to-
day activities.

4 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
The Booting Process

• When a Unix system is switched on, the processor looks at the end of the system
memory for the BIOS (Basic Input/output System) and runs it. The BIOS program is
written into permanent ROM (read-only memory) and is always available for use.
• The BIOS provides the lowest level interface to peripheral devices and controls the
first step of the booting process.
• The BIOS tests the system, looks for and checks peripherals, and then looks for a
drive to use to boot the system.
• Usually it checks the CD-ROM drive on many newer systems for bootable media, if
present, and then it looks to the hard drive.
• The order of the drives used for booting is usually controlled by BIOS setting on the
system.
• The BIOS looks for MBR (Master Boot Record) starting at the first sector on the first
hard drive, loads its contents into memory, then passes control to it.
• This MBR contains instructions on how to load the GRUB (GRand Unified
Bootloader) or LILO (Linux Loader) boot-loader, using a pre-selected operating
system.
• The MBR then loads the boot-loader, which takes over the process (if the boot-
loader is installed in the MBR).
• In the default UNIX configuration, GRUB uses the settings in the MBR to display
boot options in a menu.
• Once GRUB has received the correct instructions for the operating system to start, it
finds the necessary boot file and hands over the control of the machine to the
operating system.

Shutdown

• UNIX was not made to be shut down, but if you really want, use
the shutdown command.
• The shutdown command in Linux is used to shutdown the system in a safe way.
• When the shutdown is initiated, all logged-in users and processes are notified that
the system is going down, and no further logins are allowed.
• Only root user can execute shutdown command.

5 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Login into UNIX

• When you first connect to a Unix System, you usually see a prompt such as the
following:

login:

To log in

• To log in in Unix you require your user id (user Identification) and password.
• Type your user id at the login prompt, and then press ENTER. Your user id is case-
sensitive.
• Type your password at the password prompt, and then press ENTER. Your
password is also case-sensitive.
• If you provide the correct user id and password, then you will be allowed to enter
into the system.
• Read the information and messages that comes up on the screen which is as
follows:

login: jpm
jpm's password:
Last login: Sun Dec 5 09:32:32 2021 from
62.61.164.73
$

• You will be provided with a command prompt ($ prompt) where you type all your
commands. For example, to check calendar, you need to type the cal command as
follows:
$ cal
December 2021
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
$

Change Password

• All UNIX systems require passwords to ensure that your files and data remain
yours and system itself is secure from hackers and crackers.

6 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
• Following are the steps to change your password:
o Step 1 − To start, type passwd at the command prompt as shown below.
o Step 2 − Enter your old password, the one you're currently using.
o Step 3 − Type in your new password. Always keep your password complex
enough so that nobody can guess it. But make sure, you remember it.
o Step 4 − You must verify the password by typing it again.

$ passwd
Changing password for jpm
(current) Unix password: ******
New UNIX password: *******
Retype new UNIX password: *******
passwd: all authentication tokens updated successfully
$

Listing Directories and Files

• 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.
• You can use the ls command to list out all the files or directories available in a
directory. Following is the example of using ls command with -l option.

$ ls -l
total 19621
drwxrwxr-x 2 jpm jpm 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 jpm jpm 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 jpm jpm 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007
urlspedia.tar
$
• Here entries starting with d..... represent directories. For example, uml, univ and
urlspedia are directories and rest of the entries are files.

Who Are You?

• While you're logged into the system, you might be willing to know: Who am I?
• The easiest way to find out "who you are" is to enter the whoami command:

7 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
$ whoami
jpm
$

Who is logged in?

• Sometime you might be interested to know who is logged in to the computer at the
same time.
• There are three commands available to get you this information, based on how
much you wish to know about the other users: users, who, and w.

$ users
jpm bablu sameer

$ who
jpm ttyp0 Oct 8 14:10
bablu ttyp2 Oct 4 09:08
sameer ttyp4 Oct 8 12:09

$
• Try the w command on your system to check the output. This lists down information
associated with the users logged in the system.

Logging Out

• When you finish your session, you need to log out of the system. This is to ensure
that nobody else accesses your files.
• Just type the logout command at the command prompt, and the system will clean
up everything and break the connection.

8 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
System processes
• Whenever you issue a command in UNIX, it creates, or starts, a new process.
When you give the ls command to list the directory contents, you started a process.
• A process, in simple terms, is an instance of a running program.
• The operating system tracks processes through a five-digit ID number known as
the pid or the process ID. Each process in the system has a unique pid.
• pids eventually repeat because all the possible numbers are used up and the next
pid rolls or starts over.
• At any point of time, no two processes with the same pid exist in the system
because it is the pid that UNIX uses to track each process.

Starting a Process
• When you start a process (run a command), there are two ways you can run it:
o Foreground Processes
o Background Processes

Foreground Processes
• By default, every process that you start runs in the foreground. It gets its input from
the keyboard and sends its output to the screen.
• You can see this happen with the ls command. If you wish to list all the files in your
current directory, you can use the following command:

$ls ch*.doc
This would display 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

• The process runs in the foreground, the output is directed to screen, and if
the ls command wants any input (which it does not), it waits for it from the
keyboard.
• While a program is running in the foreground and is time-consuming, no other
commands can be run (start any other processes) because the prompt would not be
available until the program finishes processing and comes out.

Background Processes
• A background process runs without being connected to your keyboard. If the
background process requires any keyboard input, it waits.
• The advantage of running a process in the background is that you can run other
commands; you do not have to wait until it completes to start another.

9 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
• The simplest way to start a background process is to add an ampersand (&) at the
end of the command.

$ls ch*.doc &


This displays all those 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

• Here, if the ls command wants any input (which it does not), it goes into a stop state
until we move it into the foreground and give it the data from the keyboard.

Listing Running Processes


• It is easy to see your own processes by running the ps (process status) command
as follows:
$ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps
• One of the most commonly used flags for ps is the -f (f for full) option, which
provides more information as shown in the following example:
$ps -f
UID PID PPID C STIME TTY TIME CMD
root 6738 3662 0 10:23:03 pts/6 0:00 first_one
root 6739 3662 0 10:22:54 pts/6 0:00 second_one
root 3662 3657 0 08:10:53 pts/6 0:00 -ksh
root 6892 3662 4 10:51:50 pts/6 0:00 ps –f

• Here is the description of all the fields displayed by ps -f command:

o UID-User ID that this process belongs to (the person running it)


o PID- Process ID
o PPID- Parent process ID (the ID of the process that started it)
o C- CPU utilization of process
o STIME- Process start time
o TTY-Terminal type associated with the process
o TIME- CPU time taken by the process
o CMD- The command that started this process

10 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
• There are other options which can be used along with ps command:

o -a - Shows information about all users


o -x - Shows information about processes without terminals
o -u - Shows additional information like -f option
o -e - Displays extended information

Stopping Processes
• Ending a process can be done in several different ways. Often, from a console-
based command, sending a CTRL + C keystroke will exit the command. This works
when the process is running in the foreground mode.
• If a process is running in the background, you should get its Job ID using
the ps command. After that, you can use the kill command to kill the process as
follows:
$ps -f
UID PID PPID C STIME TTY TIME CMD
root 6738 3662 0 10:23:03 pts/6 0:00 first_one
root 6739 3662 0 10:22:54 pts/6 0:00 second_one
root 3662 3657 0 08:10:53 pts/6 0:00 -ksh
root 6892 3662 4 10:51:50 pts/6 0:00 ps -f
$kill 6738
Terminated
• Here, the kill command terminates the first_one process. If a process ignores a
regular kill command, you can use kill -9 followed by the process ID as follows:
$kill -9 6738
Terminated

Parent and Child Processes


• Each UNIX process has two ID numbers assigned to it: The Process ID (pid) and
the Parent process ID (ppid). Each user process in the system has a parent
process.
• Most of the commands that you run have the shell as their parent process. Check
the ps -f example where this command listed both the process ID and the parent
process ID.

Zombie and Orphan Processes


• Normally, when a child process is killed, the parent process is updated via
a SIGCHLD signal. Then the parent can do some other task or restart a new child as
needed.

11 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
• However, sometimes the parent process is killed before its child is killed. In this
case, the init process, the "parent of all processes", becomes the new PPID
(parent process ID).
• These processes whose parent process is killed are called orphan processes.
• A process which has finished the execution but still has entry in the process table to
report to its parent process is known as a zombie process.
• These processes are dead and essentially removed from the system but still
somehow reside in the memory. These processes are different from the orphan
processes.

Daemon Processes
• Daemons are system-related background processes that often run with the
permissions of root and services requests from other processes.
• To be precise, a daemon is a process that runs in the background, usually
waiting for something to happen that it is capable of working with.
• For example, a printer daemon process waiting for print commands.
• If you have a program that calls for lengthy processing, then it’s worth to make it a
daemon and run it in the background.

UNIX commands
• Unix commands can be divided into two categories.
o Internal commands
o External Commands
1 Internal Commands: Commands built-in into the shell are known as internal
commands. The shell does not create a separate process to run internal commands.
Some examples are cd, echo, pwd, etc.
2 External Commands: Commands stored in /bin directory are known as external
commands. External commands require the shell to create a new process. Some
examples are Is, cat, date, grep, etc.

Some commonly used UNIX Commands


• After starting UNIX, a command prompt will come as $ (dollar symbol). Just type out the
commands and see the results:

12 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
1 mkdir: Creates new directories in a file system.

$ mkdir [OPTION] <directory name>

Options:
-p: Create parent directories as necessary. When this option is specified, no error is
reported if a directory already exists.
-v: Verbose output. Print a message for each created directory.

2 cd: This command in Linux known as change directory command. It is used to change
current working directory.

cd /: This command is used to change directory to the root directory. The root
directory is the first directory in your file system hierarchy.

cd ~ : This command is used to change directory to the home directory.

cd .. : This command is used to move to the parent directory of current directory or the
directory one level up from the current directory. “..” represents parent directory.

3 mv: Stands for move. mv is used to move one or more files or directories from one
place to another in file system like UNIX. It has two distinct functions:
(i) It renames a file or folder.
(ii) It moves group of files to different directory.

$: mv sourcedir desinitiondir

4 pwd: Stands for Print Working Directory. It prints the path of the working directory,
starting from the root.
5 rmdir: This command is used remove empty directories from the file system in Linux.
▪ The rmdir command removes each and every directory specified in the command
line only if these directories are empty.
▪ So, if the specified directory has some directories or files in it then this cannot be
removed by rmdir command.
6 rm: Stands for remove here. rm command is used to remove objects such as files,
directories, symbolic links and so on from the file system like UNIX. By default, it does
not remove directories.
▪ With –r (or -R) option rm command will delete all the files and sub-directories
recursively of the parent directory.

13 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
▪ At each stage it deletes everything it finds. Normally, rm wouldn’t delete the
directories but when used with this option, it will delete.

7 chmod: This command is used to change the access mode of a file. The name is an
abbreviation of change mode.

$ chmod [reference][operator][mode] file...

▪ The references are used to distinguish the users to whom the permissions apply
i.e. they are list of letters that specifies whom to give permissions. The references
are represented by one or more of the following letters:

Reference Class Description

u owner file's owner


g group users who are members of the file's group
o others neither the file's owner nor members of the file's group
a all All three of the above, same as ugo

▪ The operator is used to specify how the modes of a file should be adjusted. The
following operators are accepted:

Operator Description

+ Adds the specified modes to the specified classes


- Removes the specified modes from the specified classes
= The modes specified are the exact modes for the specified classes

▪ The modes indicate which permissions are to be granted or removed from the
specified classes. There are three basic modes which correspond to the basic
permissions:

r Permission to read the file.


w Permission to write (or delete) the file.
x Permission to execute the file, or, in the case of a directory, search it.
$ ls -l filename.txt

Output:
-rw-r--r-- 1 linux users 12.0K Apr 8 20:51 filename.txt

▪ Numeric Permissions: chmod can also be used as attributed by Numeric


Permissions:

14 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody

▪ Some Examples:

$ chmod u+x file1 : grants execute permission to the user or owner


$ chmod a+x file1 : grants execute permission for all the classes of
users.
8 ls - Short listing of directory contents.

Options

-a list hidden files


-d list the name of the current directory
-g show group ownership of file in long listing
-i print the inode number of each file
-l long listing giving details about files and directories
-R list all subdirectories encountered
-t sort by time modified instead of name

9 cp - Copy files

cp myfile yourfile

▪ Copy the files "myfile" to the file "yourfile" in the current working directory. This
command will create the file "yourfile" if it doesn't exist. It will normally overwrite it
without warning if it exists.

cp -i myfile yourfile

▪ With the "-i" option, if the file "yourfile" exists, you will be prompted before it is
overwritten.

15 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
cp -i /data/myfile

▪ Copy the file "/data/myfile" to the current working directory and name it "myfile".
Prompt before overwriting the file.
10 cat: Sends file contents to standard output. This is a way to list the contents of short
files to the screen. It works well with piping.
11 wc: Print byte, word, and line counts of a file.

$ wc f1

Options

-l : display only lines


-c : display only total no. of characters
-w : display only words.

12 cal month year: Prints a calendar for the specified month of the specified year.
13 clear: Clears the terminal screen.
14 man command: Prints the specified manual page. It displays the usage of a command.
15 reboot: Reboots the system (requires root privileges).
16 shutdown minutes:

shutdown -r minutes

▪ Shuts down the system after the specified number of minutes elapses (requires root
privileges). The -r option causes the system to be rebooted once it has shut down.

16 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Process management in UNIX
• The following system calls are used for basic process management.
1. fork(): A parent process uses fork to create a new child process. The child process
is a copy of the parent. After fork, both parent and child execute the same program
but as a separate process.
2. exec(): The child may use exec after a fork to replace the process’ memory space
with a new program.
3. exit(): Terminates the process with an exit status.
4. wait(): The parent may use wait to suspend execution until a child terminates. Using
wait the parent can obtain the exit status of a terminated child.

1. fork() and exit()

• In traditional Unix the only way to create a process is using the fork() system call. The
new process gets a copy of the current program with a new process id (pid).
• In the parent process, fork() returns and delivers the new processes pid as a result.
• In the new process the fork() system call returns value 0.
• So fork() is a special system call. You call it once, but the function returns twice: Once
in the parent, and once in the child process.
• fork() increases the number of processes in the system by one. Every Unix process
always starts their existence by returning from a fork() system call with a 0 result,
running the same program as the parent process.

Example-1
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void main() {
pid_t pid = 0;
pid = fork();
if (pid == 0) {
printf("I am the child.\n");
}

17 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
if (pid > 0) {
printf("I am the parent, the child is %d.\n", pid);
}
if (pid < 0) {
perror("In fork():");
}
exit(0);
}

2. wait()

• Child process ends with an exit(0). The 0 is the exit status of our program. We need to
make the parent process pick up this value. We need a new system call for this. This
system call is wait().

18 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Example-2

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
void main() {
pid_t pid = 0;
int status;
pid = fork();

if (pid == 0)
{
printf("I am the child.\n");
sleep(10);
printf("I am the child, 10 seconds later.\n");
}

if (pid > 0)
{
printf("I am the parent, the child is %d.\n", pid);
pid = wait(&status);
printf("End of process %d: ", pid);

if(WIFEXITED(status))
{
printf("The process ended with exit(%d).\n",
WEXITSTATUS(status));
}

if(WIFSIGNALED(status))
{
printf("The process ended with kill -%d.\n",
WTERMSIG(status));
}
}
if (pid < 0)
{
perror("In fork():");
}
exit(0);
}

19 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Output
I am the child.
I am the parent, the child is 17399.
I am the child, 10 seconds later.
End of process 17399: The process ended with exit(0).

• The variable status is passed to the system call wait() as a reference parameter, and
will be overwritten by it.
• The value is a bitfield, containing the exit status and additional reasons explaining
how the program ended.
• To decode this, C offers a number of macros with predicates such as WIFEXITED()
or WIFSIGNALED().
• We also get extractors, such as WEXITSTATUS() and WTERMSIG().
• wait() also returns the pid of the process that terminated, as a function result.
• wait() stops execution of the parent process until either a signal arrives or a child
process terminates.

3. exec()
• The available exec functions along with their function parameters are given below:

int execl(const char *path, const char *arg, …, NULL);


int execlp(const char *file, const char *arg, …, NULL );
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execle(const char *path, const char *arg, …, NULL, char * const
envp[] );
int execve(const char *file, char *const argv[], char *const envp[]);

4. execl() System Function

• In execl() system function takes the path of the executable binary file (i.e. /bin/ls) as
the first and second argument.
• Then, the arguments (i.e. -ls,-l, /home) that you want to pass to the executable
followed by NULL. Then execl() system function runs the command and prints the
output.
• If any error occurs, then execl() returns -1. Otherwise, it returns nothing.

20 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore
Example-3
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/wait.h>

main(void) {
pid_t pid = 0;
int status;

pid = fork();
if (pid == 0) {
printf("I am the child.\n");
execl("/bin/ls", "ls", "-l", "/home", NULL);
perror("In exec(): ");
}
if (pid > 0)
{
printf("I am the parent, and the child is %d.\\n", pid);
pid = wait(&status);
printf("End of process %d: ", pid);
if (WIFEXITED(status))
{
printf("The process ended with exit(%d).\\n",
WEXITSTATUS(status));
}
if (WIFSIGNALED(status)) {
printf("The process ended with kill -%d.\\n",
WTERMSIG(status));
}
}
if (pid < 0) {
perror("In fork():");
}

exit(0);
}

= XXX =

21 Jyoti Prakash Mohanta, Asst. Prof. of Computer Science, F.M. Auto. College, Balasore

You might also like