Linux Programming Lab Manual-New Syllabus
Linux Programming Lab Manual-New Syllabus
III-BTECH
Contents
1. a)
2. Write a C program that makes a copy of a file using standard I/O, and system
calls
3. Write a C program to emulate the UNIX ls l command.
4. Write a C program that illustrates how to execute two commands concurrently
with a command pipe. Ex: - ls l | sort
5. Write a C program that illustrates two processes communicating using shared
memory
6. Write a C program to simulate producer and consumer problem using
semaphores
7. Write C program to create a thread using pthreads library and let it run its
function.
8. Write a C program to illustrate concurrent execution of threads using pthreads
Library
Page 2
1.
WHO Command
who command displays information about the current status of system.
who options file
Who as default prints login names of users currently logged in.
Options
o
o
o
o
o
o
Cat Command
cat filename
cat is used to display the contents of the file.
cat is used to create file
cat> filename
Cd Command.
Cd directoryname
Will change directory from current directory to specified directory.
Page 3
Cal command
cal command will print the calendar on current month by default. If you want to
print calendar of august of 1965. That's eighth month of 1965.
cal 8 1965 will print following results.
August 1965
S M Tu
W Th
F S
6 7
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Pwd command.
pwd command will print your home directory on screen, pwd means print working
directory.
/home/satish
Ls command
ls command is most widely used command and it displays the contents of directory.
options
ls will list all the files in your home directory, this command has many
options.
ls -l will list all the file names, permissions, group, etc in long format.
ADITYA ENGINEERING COLLEGE
Page 4
ls -a will list all the files including hidden files that start with . .
ls -lt will list all files names based on the time of creation, newer files bring
first.
ls -Fxwill list files and directory names will be followed by slash.
ls -Rwill lists all the files and files in the all the directories, recursively.
ls -R | more will list all the files and files in all the directories, one page at a
time.
Mkdir command
mkdir aditya
will create new directory, i.e. here aditya directory is created.
Cd command
cd aditya
will change directory from current directory to aditya directory. Use pwd to check
your current directory and ls to see if aditya directory is there or not.
Chmod command
chmod
cal.txt.
initially when this file will be created the permissions for this file depends upon
umask set in your profile files. As you can see this file has
Page 5
ls -la cal.txt
-rw-rw-rw- 1 ssb dxidev
In this line above I have -rw-rw-rw- meaning respectively that owner can read and
write file, member of the owner's group can read and write this file and anyone else
connected to this system can read and write this file., next ssb is owner of this file
dxidev is the group of this file, there are 135 bytes in this file, this file was created
on December 3 at time16:14 and at the end there is name of this file. Learn to read
these permissions in binary, like this for example Decimal 644 which is 110 100 100
in binary meand rw-r--r-- or user can read,write this file, group can read only,
everyone else can read only. Similarly, if permissions are 755 or 111 101 101 that
means rwxr-xr-x or user can read, write and execute, group can read and execute,
everyone else can read and execute. All directories have d in front of permissions.
So if you don't want anyone to see your files or to do anything with it use chmod
command and make permissions so that only you can read and write to that file, i.e.
chmod 600 filename.
mkdir Command
mkdir dirname
rmdir Command
rmdir dirname
Removes directory
Date command.
Date displays todays date, to use it type date at prompt.
Sun Dec 7 14:23:08 EST 1997
is similar to what you should see on screen.
Page 6
PS command
ps command is probably the most useful command for systems administrators. It
reports information on active processes.
ps options
Options.
-a Lists all processes in system except processes not attached to terminals.
-e Lists all processes in system.
-f Lists a full listing.
-j print process group ID and session ID.
Shutdown command.
Shutdown command can only be executed by root. To gracefully bring down a
system, shutdown command is used.
options.
-gn use a grace-period of n seconds (default is 60).
-ik tell the init command to place system in a state k. o s single-user state
(default)
0 shutdown for power-off.
1 like s, but mount multi-user file systems.
5 stop system, go to firmware mode.
6 stop system then reboot.
-y suppress the default prompt for confirmation.
MV Command
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
mv
mv
filename1
filename2
Page 7
cp Command
process
More Command
more file perusal filter for crt viewing
b) Study of VI Editor
Editor
An editor allows the users to see a portion of a file on the screen and to modify
characters and lines by simply typing at the cursor position.
Vi editor
Vi stands for visual
It is a full screen editor and allows the user to view and edit the entire
document at the same time.
Vi is case sensitive.
It has powerful undo features.
Modes of Vi editor
ADITYA ENGINEERING COLLEGE
Page 8
Syntax: vi filename
Moving the cursor
The cursor movement commands are:
Command
Action
H or backspace
l or spacebar
K or -
Up one line
J or +
#b
Page 9
#e
F[character]
T[character]
0 or ^
#$
Purpose
Page 10
Deleting Text
For deleting a character, move the cursor to the character , press x. The
character will disappear.
Command
Purpose
X
nx
#x
#X
D$ or d
D0
#dd
#dw
Page 11
C) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system
The shell provides you with an interface to the UNIX system. It gathers input from
you and executes programs based on that input. When a program finishes executing, it
displays that program's output.
A shell is an environment in which we can run our commands, programs, and shell
scripts. There are different flavors of shells, just as there are different flavors of
operating systems. Each flavor of shell has its own set of recognized commands and
functions.
Shell Prompt:
The prompt, $, which is called command prompt, is issued by the shell. While the
prompt is displayed, you can type a command.
The shell reads your input after you press Enter. It determines the command you want
executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words.
Following is a simple example of date command which displays current date and
time:
$date
Thu Jun 25 08:30:19 MST 2009
Page 12
You can customize your command prompt using environment variable PS1 explained in Environment
tutorial.
Shell Types:
In UNIX there are two major types of shells:
The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:
Page 13
means many software developers are familiar with it. It offers features such as input
and output redirection, shell scripting with string and integer variables, and condition
testing and looping.
bash
The popularity of sh motivated programmers to develop a shell that was compatible
with it, but with several enhancements. Linux systems still offer the sh shell, but
"bash" -- the "Bourne-again Shell," based on sh -- has become the new default
standard. One attractive feature of bash is its ability to run sh shell scripts unchanged.
Shell scripts are complex sets of commands that automate programming and
maintenance chores; being able to reuse these scripts saves programmers time.
Conveniences not present with the original Bourne shell include command
completion and a command history.
Page 14
1. /bin
The /bin directory is for User Binaries. It is where many of the most common Linux
commands are stored. Specifically, this is where the single user mode binaries are
stored.
2. /sbin
This directory is almost exactly like the /bin directory, with one exception. The
binaries here are primarily used by Administrators for system maintenance.
3. /etc
The configuration files for your programs and operating system are stored in /etc.
4. /dev
This is where all of the device files are located. For example, this is the directory that
you would call to in order to mount a drive with a command like: mount /dev/sda2
/mnt/backup
5. /proc
The /proc directory is one of the most interesting in the whole Linux File System. It
is actually its own virtual file system with a massive amount of text information about
system processes.
6. /var
ADITYA ENGINEERING COLLEGE
Page 15
This is where all of the variable files are stored. Most commonly, this is where log
files and web server files are stored.
7. /tmp
These are simply temporary files.
8. /usr
Programs installed by single users get stored here.
9. /home
This is where all of the user home directories are except for the root users home
directory which is /root.
10. /boot
The files that make up the boot loader go in /boot. Everything from boot loader
menus, to the actual kernel files are stored here.
11. /lib
All of the binary files that are located in /bin and /sbin are supported by the library
files located in /lib.
12. /opt
/opt is short for optional. It is the directory where individual vendors can install
optional add-on software for the operating system.
13. /mnt
The /mnt directory is the mount point that system administrators can use to mount file
systems temporarily.
14. /media
The /media directory serves the same purpose as the /mnt directory except it is
specifically for removable devices and can be used by non administrators.
15. /srv
The /srv directory contains server specific service files.
e) Study of .bashrc, /etc/bashrc and Environment variables
.bashrc is a shell script that Bash runs whenever it is started interactively. You can put
any command in that file that you could type at the command prompt.
You put commands here to set up the shell for use in your particular environment, or
to customize things to your preferences. A common thing to put
in .bashrc are aliases that you want to always be available.
Page 16
Like .bash_profile you will also commonly see a .bashrc file in your home directory.
This file is meant for setting command aliases and functions used by bash shell users.
Just like the /etc/profile is the system wide version of .bash_profile.
The /etc/bashrc for Red Hat and/etc/bash.bashrc in Ubuntu is the system wide version
of .bashrc.
Interestingly enough in the Red Hat implementation the /etc/bashrc also executes the
shell scripts within/etc/profile.d but only if the users shell is a Interactive Shell (aka
Login Shell)
An environment variable is a named object that contains data used by one or more
applications. In simple terms, it is a variable with a name and a value. The value of an
environmental variable can for example be the location of all executable files in the
file system, the default editor that should be used, or the system locale settings. Users
new to Linux may often find this way of managing settings a bit unmanageable.
However, environment variables provide a simple way to share configuration settings
between multiple applications and processes in Linux.
Page 17
2. Write a C program that makes a copy of a file using standard I/O, and system
calls
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_SIZE 8192
int main(int argc, char* argv[]) {
int input_fd, output_fd; /* Input and output file descriptors */
ssize_t ret_in, ret_out; /* Number of bytes returned by read() and write() */
char buffer[BUF_SIZE]; /* Character buffer */
/* Are src and dest file name arguments missing */
if(argc != 3){
printf ("Usage: cp file1 file2");
return 1;
}
/* Create input file descriptor */
input_fd = open (argv [1], O_RDONLY);
if (input_fd == -1) {
perror ("open");
return 2;
}
/* Create output file descriptor */
output_fd = open(argv[2], O_WRONLY | O_CREAT, 0644);
if(output_fd == -1){
perror("open");
return 3;
}
/* Copy process */
while((ret_in = read (input_fd, &buffer, BUF_SIZE)) > 0){
ADITYA ENGINEERING COLLEGE
Page 18
Page 19
Page 20
Page 21
Page 22
The key argument is a access value associated with the semaphore ID. The size
argument is the size in bytes of the requested shared memory. The shmflg argument
specifies the initial access permissions and creation control flags.
When the call succeeds, it returns the shared memory segment ID. This call is also
used to get the ID of an existing shared segment (from a process requesting sharing of
some existing memory portion).
Algorithm:
1. Start
2. create shared memory using shmget( ) system call
3. if success full it returns positive value
4. attach the created shared memory using shmat( ) system
call
5. write to shared memory using shmsnd( ) system call
6. read the contents from shared memory using shmrcv( )
system call
7. End .
shm_server.c
-- simply creates the string and shared memory portion.
shm_client.c
-- attaches itself to the created shared memory portion and uses the string
shm_server.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
/*
* We'll name our shared memory segment
ADITYA ENGINEERING COLLEGE
Page 23
* "5678".
*/
key = 5678;
/*
* Create the segment.
*/
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/*
* Now put some things into the memory for the
* other process to read.
*/
s = shm;
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = NULL;
/*
* Finally, we wait until the other process
* changes the first character of our memory
* to '*', indicating that it has read what
* we put there.
*/
while (*shm != '*')
sleep(1);
exit(0);
}
Page 24
shm_client.c
/*
* shm-client - client program to demonstrate shared memory.
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
main()
{
int shmid;
key_t key;
char *shm, *s;
/*
* We need to get the segment named
* "5678", created by the server.
*/
key = 5678;
/*
* Locate the segment.
*/
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/*
* Now read what the server put in the memory.
*/
for (s = shm; *s != NULL; s++)
putchar(*s);
putchar('\n');
ADITYA ENGINEERING COLLEGE
Page 25
/*
* Finally, change the first character of the
* segment to '*', indicating we have read
* the segment.
*/
*shm = '*';
exit(0);
}
Page 26
ALGORITHM:
1. Start the process
2. Initialize buffer size
3. Consumer enters, before that producer buffer was not empty.
4. Producer enters, before check consumer consumes the buffer.
5. Stop the process.
PROGRAM:
#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n"); while(1) {
printf("\nENTER YOUR CHOICE\n");
scanf("%d",&n); switch(n) {
case 1:
if((mutex==1)&&(empty!=0))
producer();
else printf("BUFFER IS FULL"); break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else printf("BUFFER IS EMPTY"); break;
case 3: exit(0); break;
}
}
}
int wait(int s)
{
return(--s);
ADITYA ENGINEERING COLLEGE
Page 27
}
int signal(int s)
{
return(++s);
}
void producer() { mutex=wait(mutex); full=signal(full); empty=wait(empty); x++;
printf("\nproducer produces the item%d",x); mutex=signal(mutex);
}
void consumer()
{ mutex=wait(mutex); full=wait(full); empty=signal(empty); printf("\n consumer
consumes item%d",x); x--; mutex=signal(mutex);
}
OUTPUT:
[root@localhost ~]# ./a.out 1.PRODUCER 2.CONSUMER 3.EXIT
ENTER YOUR CHOICE
1producer produces the item1
ENTER YOUR CHOICE
1producer produces the item2
ENTER YOUR CHOICE
2consumer consumes item2
ENTER YOUR CHOICE
2consumer consumes item1
ENTER YOUR CHOICE
2BUFFER IS EMPTY
ENTER YOUR CHOICE
Page 28
7. Write C program to create a thread using pthreads library and let it run
its function.
DESCRIPTION:
Creating a (Default) Thread
Use the function pthread_create() to add a new thread of control to the current
process. It is prototyped by:
int pthread_create(pthread\_t *tid, const pthread\_attr\_t *tattr,
void*(*start_routine)(void *), void *arg);
When an attribute object is not specified, it is NULL, and the default thread is created
with the following attributes:
It is unbounded
It is nondetached
It has a a default stack and stack size
It inhetits the parent's priority
You can also create a default attribute object with pthread_attr_init() function, and
then use this attribute object to create a default thread.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread(void *vargp)
{
sleep(1);
printf("welcome to ADITYA ENGINEERING COLLEGE \n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread,NULL);
pthread_join(tid,NULL);
exit(0);
}
ADITYA ENGINEERING COLLEGE
Page 29
To Compile
cc filename.c l pthread
To Run
./a.out
8. Write a C program to illustrate concurrent execution of threads using
pthreads Library
Specifying Potential Parallelism in a Concurrent Programming Environment
Now that we know the orderings that we desire or would allow in our program,
how do we express potential parallelism at the programming level? Those
programming environments that allow us to express potential parallelism are known
as concurrent programming environments. A concurrent programming environment
lets us designate tasks that can run in parallel. It also lets us specify how we would
like to handle the communication and synchronization issues that result when
concurrent tasks attempt to talk to each other and share data.
Because most concurrent programming tools and languages have been the
result of academic research or have been tailored to a particular vendors products,
they are often inflexible and hard to use. Pthreads, on the other hand, is designed to
work across multiple vendors platforms and is built on top of the familiar UNIX C
programming interface. Pthreads gives you a simple and portable way of expressing
multithreading in your programs.
Page 30
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread1(void *vargp)
{
int i;
printf("thread1\n");
for(i=1;i<=100;i++)
printf("i=%d\n",i);
printf("exit from thread1\n");
return NULL;
}
void *mythread2(void *vargp)
{
int j;
printf("thread2 \n");
for(j=1;j<=100;j++)
printf("j=%d\n",j);
printf("Exit from thread2\n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread1,NULL);
pthread_create(&tid,NULL,mythread2,NULL);
pthread_join(tid,NULL);
pthread_join(tid,NULL);
exit(0);
}
Page 31