Você está na página 1de 31

LINUX PROGRAMMING LAB MANUAL

III-BTECH

COMPUTER SCIENCE AND ENGINEERING


ADITYA ENGINEERING COLLEGE

LINUX PROGRAMMING LAB MANUAL

Contents
1. a)

Study of Unix/Linux general purpose utility command list


man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time,
kill, history, chmod, chown, finger, pwd, cal, logout, shutdown.
b) Study of vi editor.
c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
d) Study of Unix/Linux file system (tree structure).
e) Study of .bashrc, /etc/bashrc and Environment variables.

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

ADITYA ENGINEERING COLLEGE

Page 2

LINUX PROGRAMMING LAB MANUAL

1.

a) Study of Unix/Linux general purpose utility command list


man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time,
kill, history, chmod, chown, finger, pwd, cal, logout, shutdown.

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

-a use all options.


-b Report information about last reboot.
-d report expired processes.
-H print headings.
-p report previously spawned processes.
-u report terminal usage.

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.

ADITYA ENGINEERING COLLEGE

Page 3

LINUX PROGRAMMING LAB MANUAL

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

LINUX PROGRAMMING LAB MANUAL

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

command is used to change permissions on a file.

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

666 or -rw-rw-rw attributes.


ADITYA ENGINEERING COLLEGE

Page 5

LINUX PROGRAMMING LAB MANUAL

ls -la cal.txt
-rw-rw-rw- 1 ssb dxidev

135 Dec 3 16:14 cal.txt

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

Makes a new directory

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.

Time Command time - time a simple command or give resource usage


The time command runs the specified program command with the given
arguments. When command finishes, time writes a message to standard error giving
timing statistics about this program run.

ADITYA ENGINEERING COLLEGE

Page 6

LINUX PROGRAMMING LAB MANUAL

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

change file name or directory location

mv

filename1

filename2

ADITYA ENGINEERING COLLEGE

Page 7

LINUX PROGRAMMING LAB MANUAL

cp Command

cp - copy files and directories

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.


cp [OPTION]... [-T] SOURCE DEST
Kill Command
The command kill sends the specified signal to the specified process or
group. If no signal is specified, the TERM signal is sent.

process

kill - terminate a process


ECHO Command
- display a line of text

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

LINUX PROGRAMMING LAB MANUAL

Vi editor works in 3 modes


Command mode
In this mode all the keys pressed by the user are interpreted to be editor
commands. No text is displayed on the screen even if corresponding keys is pressed
on the keyboard.
Insert mode
This mode permits to insert a new text, editing and replacement of existing text.
When Vi editor is in insert mode the letters typed at the keyboard are echoed on the
screen.
Escape mode
Commands typed at the command line.
Starting with Vi editor

Syntax: vi filename
Moving the cursor
The cursor movement commands are:

Command

Action

H or backspace

Left one character

l or spacebar

Right one character

K or -

Up one line

J or +

Down one line

Moves forward a word

#b

Moves back a word


ADITYA ENGINEERING COLLEGE

Page 9

LINUX PROGRAMMING LAB MANUAL

#e

Moves to the last character in the word

F[character]

Moves right to the specified character in


a line

T[character]

Moves right and places it one character


before the specified character

0 or ^

Moves to the beginning of the file

#$

Moves to the end of the file

Moves to the last line of the file

Moves to the specified line number

Editing the file

Open the file using $ vi filename


To add text at the end of the file, position the cursor at the last character of the
file.
Switch from command mode to text input mode by pressing a.
Here a stands for append.
Inserting text in the middle of the file is possible by pressing i. The editor
accepts and inserts the typed character until Esc key is pressed.
Command

Purpose

Inserts text to the left of the cursor

Inserts text at the beginning of the line


ADITYA ENGINEERING COLLEGE

Page 10

LINUX PROGRAMMING LAB MANUAL

Append text to the right of the cursor

Appends text at the end of the line

Appends a new line below

Appends a line above

Deleting Text
For deleting a character, move the cursor to the character , press x. The
character will disappear.
Command
Purpose
X

Deletes one character

nx

Deletes n number of characters

#x

Deletes on character at the cursor


position

#X

Deletes on the character before the


cursor position

D$ or d

Deletes a line from the cursor position


to the end of the line

D0

Deletes from the cursor position to the


starting of the line

#dd

Deletes the current line where the cursor


is positioned

#dw

Deletes the word from the cursor


position to the end of the word

The undo features


ADITYA ENGINEERING COLLEGE

Page 11

LINUX PROGRAMMING LAB MANUAL

u-undo the recent changes


U- undo all changes in the current line
Saving text
:w save the file and remains in edit mode
:wq save the file and quits from edit mode
:q quit without changes from edit mode
Quitting vi
Press zz or :wq in command mode.

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

ADITYA ENGINEERING COLLEGE

Page 12

LINUX PROGRAMMING LAB MANUAL

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:

Bourne shell ( sh)


Korn shell ( ksh)
Bourne Again shell ( bash)
POSIX shell ( sh)

The different C-type shells follow:


C shell ( csh)
TENEX/TOPS C shell ( tcsh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he
was at AT&T Bell Labs in New Jersey.
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to
as "the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this
reason, it is the shell of choice for writing scripts to use on several different versions
of UNIX.
sh
The Bourne shell, called "sh," is one of the original shells, developed for Unix
computers by Stephen Bourne at AT&T's Bell Labs in 1977. Its long history of use
ADITYA ENGINEERING COLLEGE

Page 13

LINUX PROGRAMMING LAB MANUAL

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.

csh and tcsh


Developers have written large parts of the Linux operating system in the C and C++
languages. Using C syntax as a model, Bill Joy at Berkeley University developed the
"C-shell," csh, in 1978. Ken Greer, working at Carnegie-Mellon University, took csh
concepts a step forward with a new shell, tcsh, which Linux systems now offer. Tcsh
fixed problems in csh and added command completion, in which the shell makes
educated "guesses" as you type, based on your system's directory structure and files.
Tcsh does not run bash scripts, as the two have substantial differences.
ksh
David Korn developed the Korn shell, or ksh, about the time tcsh was introduced. Ksh
is compatible with sh and bash. Ksh improves on the Bourne shell by adding floatingpoint arithmetic, job control, command aliasing and command completion. AT&T
held proprietary rights to ksh until 2000, when it became open source.

ADITYA ENGINEERING COLLEGE

Page 14

LINUX PROGRAMMING LAB MANUAL

d) Study of Unix/Linux file system (tree structure).

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

LINUX PROGRAMMING LAB MANUAL

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.

ADITYA ENGINEERING COLLEGE

Page 16

LINUX PROGRAMMING LAB MANUAL

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.

ADITYA ENGINEERING COLLEGE

Page 17

LINUX PROGRAMMING LAB MANUAL

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

LINUX PROGRAMMING LAB MANUAL

ret_out = write (output_fd, &buffer, (ssize_t) ret_in);


if(ret_out != ret_in){
/* Write error */
perror("write");
return 4;
}
}
/* Close file descriptors */
close (input_fd);
close (output_fd);
return (EXIT_SUCCESS);
}
Output : user@ITDS07:~$ cc Prog1.c
user@ITDS07:~$ ./a.out source_file.txt destination_file.txt

ADITYA ENGINEERING COLLEGE

Page 19

LINUX PROGRAMMING LAB MANUAL

3. Write a C program to emulate the UNIX ls l command.


#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int pid;
//process id
pid = fork(); //create another process
if ( pid < 0 )
{
//fail
printf(\nFork failed\n);
exit (-1);
}
else if ( pid == 0 )
{
//child
execlp ( /bin/ls, ls, -l, NULL ); //execute ls
}
else
{
//parent
wait (NULL);
//wait for child
printf(\nchild complete\n);
exit (0);
}
}

ADITYA ENGINEERING COLLEGE

Page 20

LINUX PROGRAMMING LAB MANUAL

4. Write a C program that illustrates how to execute two commands


concurrently with a command pipe. Ex: - ls l | sort
DESCRIPTION:
A pipe is created by calling a pipe() function.
int pipe(int filedesc[2]);
It returns a pair of file descriptors filedesc[0] is open for reading and filedesc[1]
is open for writing. This function returns a 0 if ok & -1 on error.
#include<stdio.h>
#include<stdlib.h>
void main(int argc, char *argv[])
{
int fd[2],pid,k;
k=pipe(fd);
if(k==-1)
{
perror("pipe"); exit(1);
}
pid=fork();
if(pid==0)
{
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp(argv[1],argv[1],NULL);
perror("exec1");
}
else
{
wait(2);
close(fd[1]); dup2(fd[0],0);
close(fd[0]);
execlp(argv[2],argv[2],NULL);
perror("exec1");
}
}
ADITYA ENGINEERING COLLEGE

Page 21

LINUX PROGRAMMING LAB MANUAL

5. Write a C program that illustrates two processes communicating using shared


memory
DESCRIPTION:
Shared Memory is an efficient means of passing data between programs. One
program will create a memory portion which other processes (if permitted) can
access.
The problem with the pipes, FIFOs and message queues is that for two
processes to exchange information, the information has to go through the kernel.
Shared memory provides a way around this by letting two or more processes share a
memory segment.
In shared memory concept if one process is reading into some shared memory,
for example, other processes must wait for the read to finish before processing the
data.
A process creates a shared memory segment using shmget()|. The original
owner of a shared memory segment can assign ownership to another user with
shmctl(). It can also revoke this assignment. Other processes with proper permission
can perform various control functions on the shared memory segment using shmctl().
Once created, a shared segment can be attached to a process address space using
shmat(). It can be detached using shmdt() (see shmop()). The attaching process must
have the appropriate permissions for shmat(). Once attached, the process can read or
write to the segment, as allowed by the permission requested in the attach operation.
A shared segment can be attached multiple times by the same process. A shared
memory segment is described by a control structure with a unique ID that points to an
area of physical memory. The identifier of the segment is called the shmid. The
structure definition for the shared memory segment control structures and
prototypews can be found in <sys/shm.h>.
shmget() is used to obtain access to a shared memory segment. It is prototyped by:
int shmget(key_t key, size_t size, int shmflg);

ADITYA ENGINEERING COLLEGE

Page 22

LINUX PROGRAMMING LAB MANUAL

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

LINUX PROGRAMMING LAB MANUAL

* "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);
}

ADITYA ENGINEERING COLLEGE

Page 24

LINUX PROGRAMMING LAB MANUAL

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

LINUX PROGRAMMING LAB MANUAL

/*
* Finally, change the first character of the
* segment to '*', indicating we have read
* the segment.
*/
*shm = '*';
exit(0);
}

ADITYA ENGINEERING COLLEGE

Page 26

LINUX PROGRAMMING LAB MANUAL

6. Write a C program to simulate producer and consumer problem using


Semaphores

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

LINUX PROGRAMMING LAB MANUAL

}
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

ADITYA ENGINEERING COLLEGE

Page 28

LINUX PROGRAMMING LAB MANUAL

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

LINUX PROGRAMMING LAB MANUAL

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.

ADITYA ENGINEERING COLLEGE

Page 30

LINUX PROGRAMMING LAB MANUAL

#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);
}

ADITYA ENGINEERING COLLEGE

Page 31

Você também pode gostar