linux programming lab manual-new syllabus

Upload: kurumeti-naga-surya-lakshmana-kumar

Post on 26-Feb-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    1/31

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    2/31

    Contents

    1.a) Study of Unix/Linux general purpose utility command listman,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 concurrentlywith a command pipe. Ex: - ls l | sort

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

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

    7. Write C program to create a thread using pthreads library and let it run itsfunction.

    8. Write a C program to illustrate concurrent execution of threads using pthreadsLibrary

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    3/31

    1. a) Study of Unix/Linux general purpose utility command listman,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.

    whooptions file

    Who as default prints login names of users currently logged in.

    Options

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

    Cat Command

    cat filenamecat is used to display the contents of the file.

    cat is used to create filecat> filename

    Cd Command.

    Cd directoryname

    Will change directory from current directory to specified directory

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    4/31

    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

    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

    Pwd command.

    pwd command will print your home directory on screen, pwd means print workingdirectory.

    /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 manyoptions.

    ls -l will list all the file names, permissions, group, etc in long format.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    5/31

    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 bringfirst.

    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 atime.

    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 checkyour 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.

    initially when this file will be created the permissions for this file depends uponumask set in your profile files. As you can see this file has

    666 or -rw-rw-rw attributes.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    6/31

    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 andwrite file, member of the owner's group can read and write this file and anyone elseconnected to this system can read and write this file., next ssb is owner of this filedxidev is the group of this file, there are 135 bytes in this file, this file was createdon December 3 at time16:14 and at the end there is name of this file. Learn to readthese permissions in binary, like this for example Decimal 644 which is 110 100 100in 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 thatmeans 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 chmodcommand and make permissions so that only you can read and write to that file, i.e.chmod 600 filename.

    mkdir Command

    Makes a new directory

    rmdir Command

    Removes directory

    Date command.

    Date displays todays date, to use it type date at prompt.Sun Dec 7 14:23:08 EST 1997is 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 givenarguments. When command finishes, time writes a message to standard error givingtiming statistics about this program run.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    7/31

    PS command

    ps command is probably the most useful command for systems administrators. Itreports 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 asystem, 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

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    8/31

    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 processgroup. If no signal is specified, the TERM signal is sent.

    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 entiredocument at the same time.

    Vi is case sensitive.

    It has powerful undo features.

    Modes of Vi editor

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    9/31

    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

    I Moves forward a word

    #b Moves back a word

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    10/31

    #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

    L Moves to the last line of the file

    G 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 thefile.

    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 editoraccepts and inserts the typed character until Esc key is pressed.

    Command Purpose

    I Inserts text to the left of the cursor

    I Inserts text at the beginning of the line

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    11/31

    A Append text to the right of the cursor

    A Appends text at the end of the line

    O Appends a new line below

    O 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 thecursor 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 cursoris positioned

    #dw Deletes the word from the cursor

    position to the end of the word

    The undo features

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    12/31

    u-undo the recent changes

    U- undo all changes in the current lineSaving 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 ofoperating 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 ofcharacters. Spaces and tabs separate words.

    Following is a simple example of date command which displays current date and

    time:

    $date

    ThuJun2508:30:19MST 2009

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    13/31

    You can customize your command prompt using environment variable PS1 explained in Environmenttutorial.

    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

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    14/31

    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 floating-

    point arithmetic, job control, command aliasing and command completion. AT&T

    held proprietary rights to ksh until 2000, when it became open source.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    15/31

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

    1. /binThe /bin directory is for User Binaries. It is where many of the most common Linuxcommands are stored. Specifically, this is where the single user mode binaries arestored.2. /sbinThis directory is almost exactly like the /bin directory, with one exception. Thebinaries 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. /devThis is where all of the device files are located. For example, this is the directory thatyou would call to in order to mount a drive with a command like: mount /dev/sda2

    /mnt/backup5. /procThe /proc directory is one of the most interesting in the whole Linux File System. Itis actually its own virtual file system with a massive amount of text information aboutsystem processes.

    6. /var

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    16/31

    This is where all of the variable files are stored. Most commonly, this is where logfiles and web server files are stored.7. /tmp

    These are simply temporary files.8. /usrPrograms installed by single users get stored here.9. /homeThis is where all of the user home directories are except for the root users homedirectory which is /root.10. /bootThe files that make up the boot loader go in /boot. Everything from boot loadermenus, to the actual kernel files are stored here.

    11. /libAll of the binary files that are located in /bin and /sbin are supported by the libraryfiles located in /lib.12. /opt

    /opt is short for optional. It is the directory where individual vendors can installoptional add-on software for the operating system.13. /mntThe /mnt directory is the mount point that system administrators can use to mount filesystems temporarily.

    14. /mediaThe /media directory serves the same purpose as the /mnt directory except it isspecifically for removable devices and can be used by non administrators.15. /srvThe /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.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    17/31

    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 anenvironmental 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.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    18/31

    2. Write a C program that makes a copy of a file using standard I/O, and system

    calls

    #include

    #include #include #include #include #include

    #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){

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    19/31

    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.cuser@ITDS07:~$ ./a.out source_file.txt destination_file.txt

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    20/31

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

    #include

    #include #include #include #include int main(){int pid; //process idpid = fork(); //create another processif ( pid < 0 )

    { //failprintf(\nFork failed\n);exit (-1);}else if ( pid == 0 ){ //childexeclp ( /bin/ls, ls, -l, NULL ); //execute ls}else

    { //parentwait (NULL); //wait for childprintf(\nchild complete\n);exit (0);}}

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    21/31

    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

    #include

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

    }

    }

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    22/31

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

    memory

    DESCRIPTION:

    Shared Memoryis 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 andprototypews can be found in .

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

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    23/31

    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. Start2. create shared memory using shmget( ) system call

    3. if success full it returns positive value4. attach the created shared memory using shmat( ) systemcall5. write to shared memory using shmsnd( ) system call6. read the contents from shared memory using shmrcv( )system call7. 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 #include #include #include

    #define SHMSZ 27main(){

    char c;int shmid;key_t key;char *shm, *s;

    /** We'll name our shared memory segment

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    24/31

    * "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

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    25/31

    shm_client.c

    /** shm-client - client program to demonstrate shared memory.

    */#include #include #include #include #define SHMSZ 27main(){

    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');

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    26/31

    /** Finally, change the first character of the

    * segment to '*', indicating we have read* the segment.*/*shm = '*';exit(0);

    }

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    27/31

    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:#includeint 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);

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    28/31

    }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 consumerconsumes item%d",x); x--; mutex=signal(mutex);}

    OUTPUT:[root@localhost ~]# ./a.out 1.PRODUCER 2.CONSUMER 3.EXITENTER YOUR CHOICE1producer produces the item1ENTER YOUR CHOICE1producer produces the item2ENTER YOUR CHOICE2consumer consumes item2ENTER YOUR CHOICE

    2consumer consumes item1ENTER YOUR CHOICE2BUFFER IS EMPTYENTER YOUR CHOICE

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    29/31

    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 to add a new thread of control to the currentprocess. 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 thethread is createdwith the following attributes:

    It is unbounded

    It is nondetached

    It has a a default stack and stack size

    It inhetits the parent's priorityYou can also create a default attribute object with function, andthen use this attribute object to create a default thread.

    #include#include#includevoid *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);

    }

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    30/31

    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? Thoseprogramming environments that allow us to express potential parallelism are knownasconcurrent programming environments. A concurrent programming environmentlets us designate tasks that can run in parallel. It also lets us specify how we wouldlike to handle the communication and synchronization issues that result whenconcurrent tasks attempt to talk to each other and share data.

    Because most concurrent programming tools and languages have been theresult 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 towork across multiple vendors platforms and is built on top of the familiar UNIX Cprogramming interface. Pthreads gives you a simple and portable way of expressingmultithreading in your programs.

  • 7/25/2019 Linux Programming Lab Manual-new Syllabus

    31/31

    #include#include#include

    void *mythread1(void *vargp){

    int i;printf("thread1\n");

    for(i=1;i