Vous êtes sur la page 1sur 54

Practical file Of UNIX & Linux programming

SUBMITTED TO: SUBMITTED BY: Er. Kumar (Lect. In C.S.E. Deptt.) 2908136 K.I.T.M., Kurukshetra C.S.E.(A3)

Jitin Roll No.Branch-

KURUKSHETRA INSTITUTE OF TECHNOLOGY & MANAGEMENT Pehowa Road, Bhor Saidan Kurukshetra

INDEX
S.NO EXPERIMENT NAME . DATE REMARK S

Practical No.1
AIM - Install Linux on a PC having some other previously installed operating system. All Operating Systems should be usable.

To install Red Hat Enterprise Linux 5 on your computer, take the following steps: Step 1:- Right Click on My Computer and go to manage option

Step 2:- Click on Disk Management option and delete a partition to make it free for RHEL installation.

Step 3:- Insert the media that youll use to boot the Red Hat Enterprise Linux 5 installation program. It can be the first Red Hat Enterprise Linux 5 CD or DVD. Step 4:- Restart the system.

Step 5:- When you see the boot prompt press ENTER key to install in graphical mode.

Step 6:- Installation Method: - Choose your installation method (like Local CDROM) and press OK

Step 7:- Press Skip to skip the Media test and start the installation.

Step 8:- Welcome Screen:- The Welcome screen does not prompt you for any input. From this screen you can access the Release Notes for Red Hat Enterprise Linux 5.0.0 by clicking on the Release Notes button. Click on the Next button to continue.

Step 9:- Language Selection: - Using your mouse, select a language to use for the installation. Once you select the appropriate language, click Next to continue.

Step 10:- Keyboard Configuration:- Using your mouse, select the correct layout type (for example, U.S. English) for the keyboard you would prefer to use for the installation and as the system default (refer to the figure below).Once you have made your selection, click Next to continue.

Step 11:- Enter the Installation Number: - Enter your Installation Number. This number will determine the package selection set that is available to the installer. If you choose to skip entering the installation number you will be presented with a basic selection of packages to install later on.

Step 12:- Create Custom Layout:Click next once you have made your selections to proceed.

Step 13:- Partitioning Your System: - If you chose to create a custom layout, you must tell the installation program where to install Red Hat Enterprise Linux. This is done by defining mount points for one or more disk partitions in which Red Hat Enterprise Linux is installed. You may also need to create and/or delete partitions at this time.

Step 14:- Adding Partitions: - To add a new partition, select the new button. Add the desired partitions.

Step 15:- Boot Loader Configuration: - To boot the system without boot media, you usually need to install a boot loader. A boot loader is the first software program that runs when a computer starts. It is responsible for loading and transferring control to the operating system kernel software. The kernel, in turn, initializes the rest of the operating system. Once youve configured your partitions, set up a boot loader. If you select No Boot Loader Will Be Installed, youll need to use a third-party boot loader such as Partition Magic or Microsofts NTLDR. Unless you want to set up a Boot Loader Password or Configure Advanced Boot Loader Options, click Next.

Step 16:- Network Configuration: - Configure your connection to the network. If you dont want the DHCP server to assign a hostname (or you dont have a DHCP server), you can assign it manually, as shown here. Click Next to move on.

Step 17:- Time Zone Configuration: - Set your time zone by selecting the city closest to your computer's physical location. Click on the map to zoom in to a particular geographical region of the world. From here there are two ways for you to select your time zone: Using your mouse, click on the interactive map to select a specific city (represented by a yellow dot). A red X appears indicating your selection.

You can also scroll through the list at the bottom of the screen to select your time zone. Using your mouse, click on a location to highlight your selection.

Step 18:- Set Root Password: - Setting up a root account and password is one of the most important steps during your installation. The root account is used to install packages, upgrade RPMs, and perform most system maintenance. Logging in as root gives you complete control over your system.

Step 19:- Package Group Selection: - There are two package customization screens available. Everyone sees the screen shown next. (The choices are slightly different for Red Hat Enterprise Linux 5 Client.) You can accept the defaults, select available options, and/or select Customize Now.

Its usually best to customize modestly (Ive selected the Customize Now option), based on the requirements on your particular Installation and Configuration exam. Click Next. (If you dont select Customize Now, skip the next step.)

Step 20:- Package Group Details.

Step 21:- Installing packages defined by the user.

The next screen congratulates you for completing the installation. The next step is to reboot your computer into RHEL. Click Reboot.

PRACTICAL NO. 2
Aim: - Familiarize with Unix/Linux logging/logout and simple commands. Login/Logout: It identifies you as a particular user. It starts up your own shell and desktop. It gives you appropriate permissions.

Syntax: - Login:
Password: $ - User, # - Root Logout is use to logout from particular user session,

who: - Show who is logged into the system. With no options, list the names
of users currently logged in, their terminal, the time they have been logged in, and the name of the host from which they have logged in. An optional system file (default is /etc/utmp) can be supplied to give additional information.

Syntax: - who [options] [file] who am i

Option: - am i: - Print the username of the invoking user. -u, --users :- Print a list of the users who are logged in.

ps: - Report on active processes. ps has three types of options. GNU long
options start with two hyphens, which are required. BSD options may be grouped and do not start with a hyphen, while Unix98 options may be grouped and require an initial hyphen. The meaning of the short options can vary depending on whether or not there is a hyphen. In options, list arguments should either be comma-separated or space-separated and placed inside double quotes. In comparing the amount of output produced, note that e prints more than a and l prints more than f for each entry.

Syntax: - ps [options]

Option: - - a: - As a, list all processes on a terminal. -d :- Select all processes except session leaders. -e, -A :- Select all processes.

cat: - Read (concatenate) one or more files and print them on standard
output. Read standard input if no files are specified or if - is specified as one of the files; input ends with EOF. You can use the > operator to combine several files into a new file, or >> to append files to an existing file. When appending to an existing file, use Ctrl-D, the end-of-file symbol, to end the session.

Syntax: -

cat [options] [files]

Options: - -b, --number-nonblank: - Number all nonblank output lines,

starting with 1.

-E, --show-ends: - Print $ at the end of each line. -n, --number :- Number all output lines, starting with 1. -s, --squeeze-blank :- Squeeze down multiple blank lines to one blank line. wc: - To count the number of characters , words & lines in particular file. Syntax: - wc[options][file] Options: - -c: - To count characters only. -w :- To count only words. -l :- To count only lines. cal: - Print a 12-month calendar (beginning with January) for the given year, or a one-month calendar of the given month and year. month ranges from 1 to 12. year ranges from 1 to 9999. With no arguments, print a calendar for the current month. Syntax: - cal [options] [[month] year] Options :- -j :- Display Julian dates (days numbered 1 to 365). -m :- Display Monday as the first day of the week. -y :- Display entire year. date: - Print the current date and time. You may specify a display format. format can consist of literal text strings (blanks must be quoted) as well as field descriptors, whose values will appear as described in the following entries (the listing shows some logical groupings). A privileged user can change the system's date and time. Syntax: - date [options] [+format] [date] Option: - -s date, --set date: - Set the date. %d: - Day of month (01-31) %h: - Same as %b. %k: - Hour in 24-hour format, without leading zeros (0-23). %l: - Hour in 12-hour format, without leading zeros (1-12). %m: - Month of year (01-12). %p: - String to indicate a.m. or p.m. %w: - Day of week (Sunday = 0). %y: - Last two digits of year (00-99). %H: - Hour in 24-hour format (00-23). %I: - Hour in 12-hour format (01-12).

echo: - Send (echo) the input string to standard output. This is the
/bin/echo command.echo also exists as a command built into bash. The following character sequences have special meanings: (\a)Alert ,(\b) Backspace,(\c) Suppress trailing newline,(\f )Form feed,(\n )Newline,(\r ) Carriage return,(\t )Horizontal tab,(\v )Vertical tab,(\\ )Literal backslash, (\nnn )The octal character whose ASCII code is nnn.

Syntax : - echo [options] [string]


Option :- -e :- Enable character sequences with special meaning. -E :- Disable character sequences with special meaning.

rm: - Delete one or more files. To remove a file, you must have write
permission in the directory that contains the file, but you need not have permission on the file itself. If you do not have write permission on the file, you will be prompted (y or n) to override. rm is often aliased to rm -i, especially for the root user, to protect against inadvertently deleting files.

Syntax: -

rm [options] files

Options: - -d, --directory :- Remove directories, even if they are not empty.
-f, --force :- Remove write-protected files without prompting. -i, --interactive :- Prompt for y (remove the file) or n (do not remove the file). uname: - Print information about the machine and operating system. Without options, print the name of the kernel (Linux). Syntax: - uname [options] Options: - -a,--all:-Combine all system information from the other options. -i, --hardware-platform :- Print the system's hardware platform. -m, --machine :- Print name of the hardware that the system is running on. -n, --nodename :- Print the machine's hostname. -o, --operating-system :- Print the operating system name. -p, --processor :- Print the type of processor. -r, --kernel-release :- Print the release number of the kernel.

ls: - List contents of directories. If no names are given, list the files in the
current directory. With one or more names, list files contained in a directory name or that match a file name. names can include filename metacharacters. The options let you display a variety of in formation in different formats. The most useful options include -F, -R, -l, and -s. Some options don't make sense together (e.g., -u and -c).

Syntax : - ls [options] [names]


Options :- -1, --format=single-column :- Print one entry per line of output. -a, --all :- List all files, including the normally hidden files whose names begin with a period.. -d, --directory :- Report only on the directory, not its contents. -f :- Print directory contents in exactly the order in which they are stored, without attempting to sort them. -h :- Print sizes in kilobytes and megabytes. -i, --inode :- List the inode for each file. -l, --format=long, --format=verbose :- Long format listing (includes permissions, owner, size, modification time, etc.). -r, --reverse :- List files in reverse order (by name or by time). -s, --size :- Print file size in blocks. -x, --format=across, --format=horizontal :- List files in rows going across the screen. -R, --recursive :- List directories and their contents recursively.

chmod: - Change the access mode (permissions) of one or more files. Only
the owner of a file or a privileged user may change the mode. mode can be numeric or an expression in the form of who opcode permission. who is optional (if omitted, default is a); choose only one opcode. Multiple modes are separated by commas.

Syntax:

chmod [options] mode files chmod [options] --reference=filename files Options: - -f, --silent, --quiet :- Do not notify user of files that chmod cannot change. -R, --recursive :- Traverse subdirectories recursively, applying changes. -v, --verbose :- Print information about each file, whether changed or not. Who
u :- User. g :- Group. o :- Other. a :- All (default). + :- Add permission. - :- Remove permission.

Opcode

Permissions

= :- Assign permission r :- Read. w :- Write. x :- Execute. s :- Set user (or group) ID. t :- Sticky bit; used on directories to prevent removal of files by non-owners. u :- User's present permission. g :- Group's present permission. o :- Other's present permission.

Alternatively, specify permissions by a three-digit octal number. The first digit designates owner permission; the second, group permission; and the third, other's permission. Permissions are calculated by adding the following octal values: 4 :- Read. 2 :- Write. 1 :- Execute. Note that a fourth digit may precede this sequence. This digit assigns the following modes: 4 :- Set user ID on execution to grant permissions to process based on the file's owner, not on permissions of the user who created the process. 2 :- Set group ID on execution to grant permissions to process based on the file's group, not on permissions of the user who created the process. 1 :- Set sticky bit.

chown: - Change the ownership of one or more files to newowner.


newowner is either a user ID number or a login name located in /etc/passwd. chown also accepts users in the form newowner:newgroup or newowner.newgroup. The last two forms change the group ownership as well. If no owner is specified, the owner is unchanged. With a period or colon but no group, the group is changed to that of the new owner. Only the current owner of a file or a privileged user may change the owner. Syntax: chown[options]newowner files chown [options] --reference=filename files Options: - -f, --silent, --quiet :- Do not print error messages about files that cannot be changed. -v, --verbose :- Print information about all files that chown attempts to change, whether or not they are actually changed. -R, --recursive :- Traverse subdirectories recursively, applying changes. chgrp: - Change the group of one or more files to newgroup. newgroup is either a group ID number or a group name located in /etc/group. Only the owner of a file or a privileged user may change the group.

Syntax: - chgrp [options] newgroup fileschgrp [options]


Options: - -f, --silent, --quiet :- Do not print error messages about
files that cannot be changed. -R, --recursive :- Traverse subdirectories recursively, applying changes.

cp: - Copy file1 to file2, or copy one or more files to the same names under
directory. If the destination is an existing file, the file is overwritten; if the destination is an existing directory, the file is copied into the directory (the directory is not overwritten). Syntax: - cp [options] file1 file2 cp [options] files directory Options: - -a, --archive :- Preserve attributes of original files where possible. -f, --force :- Remove existing files in the destination. -i, --interactive :- Prompt before overwriting destination files. -r, -R, --recursive :- Copy directories recursively. HOME: - Show the home directory, where users personal files are stored. Syntax: - $HOME pwd :- Print the full pathname of the current working directory. Syntax: - pwd clear: - Clear the terminal display. Equivalent to pressing Ctrl-L. Syntax :- clear mv: - The mv command is often aliased as mv -i in the .bashrc file, especially for the root account, to prevent inadvertently overwriting files.

Syntax: - mv[file][file2]

Options: - -b :- Back up files before removing. -f, --force :- Force the move, even if target file exists; suppress messages about restricted access modes. -i, --interactive :- Query user before removing files. -u, --update :- Do not remove a file or link if its modification date is the same as or newer than that of its replacement. mkdir: - Create one or more directories. You must have write permission in the parent directory in order to create a directory. See also rmdir. The default mode of the new directory is 0777, modified by the system or user's umask. Syntax: - mkdir [options] directories Options: - -m , --mode mode :- Set the access mode for new directories. -p, --parents :- Create intervening parent directories if they don't exist. -v, --verbose :- Print a message for each directory created. rmdir: - Delete the named directories (not the contents). directories are deleted from the parent directory and must be empty (if not, rm -r can be used instead). Syntax: - rmdir [options] directories Options: - --ignore-fail-on-non-empty :- Ignore failure to remove non-empty
directories.

-p, --parents :- Remove directories and any intervening parent directories that become empty as a result. Useful for removing subdirectory trees.

bc : - bc is a language (and compiler) whose syntax resembles that of C,


but with unlimited-precision arithmetic. bc consists of identifiers, keywords, and symbols, which are briefly described in the following entries. Examples are given at the end. Interactively perform arbitrary-precision arithmetic or convert numbers from one base to another. Input can be taken from files or read from the standard input.

Syntax : - bc [options] [files]

PRACTICAL NO. 3
Aim: - Using Bash shell develops simple programs.
1. - Write a program to perform the basic arithmetic operation. echo "Enter the two no.s" read a read b echo "Addition is:" expr $a + $b echo "Subtraction is:" expr $a - $b echo "Multiplication is:" expr $a \* $b echo "Division is:" expr $a / $b 2. - Write a program to calculate the factorial of a number. echo "Enter a number" read num i=2 fact=1 if [ $num -ge 2 ] then while [ $i -le $num ] do fact=`expr $fact \* $i` i=`expr $i + 1` done fi echo "Factoral of a number is $fact"

3. - Write a program to find greatest of three numbers. echo "Enter the three numbers" read a read b read c if test $a -gt $b -a $a -gt $c; then echo "First no is greater" elif test $a -lt $b -a $b -gt $c; then echo "Second number is largest" else echo "Third number is largest" fi 4. - Write a program to perform the basic calculator operations. echo "Enter two no.s" read a read b echo "1 for addition" echo "2 for subtraction" echo "3 for multiplication" echo "4 for division" echo "Enter your choice" read ch case "$ch" in 1) c=$((a+b)) echo "Sum of two no.s is $c" ;; 2) c=$((a-b)) echo "Subtraction of two no.s is $c" ;; 3) c=$((a*b)) echo "Mult of two no.s is $c" ;; 4) c=$((a/b)) echo "Div of two no.s is $c" ;; *) echo "Wrong choice" esac

5. - Write a program to find a number whether even or odd. echo "Enter a number" read num if [ `expr $num % 2` -eq 0 ] then echo "$num is even" else echo "$num is odd" fi

PRACTICAL NO. 4
AIM: - Familiarize with vi editor and Linux GUIs. vi editor: - There are three type of editor
ED EX VI

ED and EX are line editor, in this editor line number is assigned to the lines in a file where as vi is the text editor or screen editor. The vi editor has been part of UNIX-based systems since the 1970s, and its interface shows it. It is arguably one of the last editors to actually use a separate command mode and data entry mode; as a result, most newcomers find it unpleasant to use. The vi editor is difficult to learn at first, but once you know it, you never have to use a mouse or a function keyyou can edit and move around quickly and efficiently within files just by using the keyboard. It shows as much of the file as it can fit on screen. It is the first full screen editor which allow the user to view and edit the entire document at a time creating and editing of a file becomes easy using vi editor. Starting vi or say to invoke vi To create a file Example: - $ vi file.txt To invoke vi type vi and file name that you want to create when we type vi and the file name press enter key then vi clears the screen and display a window in which we can enter and edit text. The easiest way to learn more about vi is to start it and enter :help.

Mode of operations: - There are three mode of operation of vi editor.


Command mode: - In this mode we insert text in blank text file or editing in existing text file. Input mode also known as insertion mode. When a key is pressed of input mode it does not appear on screen but subsequent key depressions do. Insertion mode: - In this mode all key passed by user are interpreted to the editor commands that is for moving cursor for left-right topbottom etc. In this the key pressed are not displayed on screen. By default vi editor in command mode. Execute mode: - This mode is used to handle the files and perform substitutions. It always starts with columns :.

Input mode: Insert and append:i- To insert the text in a file to anywhere. I- To insert the text in a file only at the beginning of a line. a- To append the text in file any where A- To append the text at end of line Replace :r- Replace single terminal character in a file s- One character replaced by multiple characters R- Replace all text on the right of cursor position S- Replace entire line Open line: o- Line editing at below of current line O- Line editing at upper of current line

Execution mode: - These are following command.

:w- saves file and remains in editing mode :w viki.txt - Saves to file viki.txt :w! viki.txt - As above, but overwrites exiting file :w >> viki.txt - Appends current file contents to file viki.txt : n1,n4w viki.txt - Writes lines n1 to n4 to file viki.txt :.w viki.txt - Writes current line to file viki.txt :$w viki.txt - writes last line to file viki.txt :.,$w viki.txt - writes current to last line to viki.txt :x- saves file and quits editing mode :wq- same as :x :q- quit from editor without saving the buffer :q!- forcefully quit from the editor without saving the buffer :sh- escapes to UNIX shell :recover- recovers file from a crash

Navigation: - There are several navigation keys for controlling the cursor
movement. These are as: k- Moves cursor up j- Moves cursor down h- Moves cursor left l- Moves cursor right b- Moves back to beginning of word e- Moves forward to end of word w- Moves forward to beginning of word 0(zero) - moving to the beginning of a line

|- to position the cursor to certain column $- moves to end of line [Ctrl-f] - Scrolls forward [Ctrl-b] - scrolls backward [Ctrl-d] scrolls half page forward [Ctrl-u] - scrolls half page backward G goes to end of file Editing text: - The editing facilities in vi are very elaborate and involve the use of operators. There are two operators: d- Delete y- Yank (copy) d and y are not commands, but they can be used for deleting and copying entire lines. These are following commands for editing operations: x- Deletes a single character under the cursor 4x- deletes the current character as well as three characters from the right. dd- Delete the entire line 4dd - deletes the current line and the 3 lines below yy- Yank the entire line 10yy- yanks current line and 9 lines below p- Puts the data below the current line P- Puts the data above the current line J- Used to join the lines 4J- joins following 3 lines with current line u- To undo the last change made U- Reverse all change made to the current line

Repeating the last command:- the vi editor has the facility to repeat
the last command, but most editor do not have. The dot (.) Command is used for repeating both Input and Command mode that perform editing tasks.

Searching for a pattern: -vi is strong in search and replacement


activities. Searching can be made in both forward and reverse directions, and can be repeated. It is initiated from the Command mode by pressing a /, which shows up in last line as : / - For forward search ? - For backward search Command for repeating the last pattern searches are: n- Repeats search in the same direction along which previous search was made N- Repeats search in direction opposite to that along which previous search was made

Substitution: - vi offers yet another powerful feature, that of substation,


which is achieved with the ex modes command. The syntax is as:

:address/source_pattern/target_pattern/flags The source_pattern is replaced with target_pattern in all lines specified by address. The address can be one or a pair of numbers, separated by a comma. The most commonly used flag is g, which substitute all occurrences of the pattern in a line. For example: :1,$s/director/member/g The target pattern is optional. If you leave it out, then youll delete all occurrences of the source pattern in all lines matched by address. For example: :1,23s/member//g Interactive substitution:- something like to selectively replace a string. In this case, add the c (confirmatory) parameter as the flag at the end: :1,$s/director/member/gc

Disadvantages: There are no of self explanatory error message in vi if anything goes wrong then there is an error message appear. Only speaker keeps to inform that something wrong No help available in vi editor There are three mode in which vi editor work but in each mode same key create different effects vi is key sensitive. Vi can handle that maintain plain text that no fstyle in fault. No graphic just simple text file we can create, edit and print

PRACTICAL NO. 5
AIM: - Develop some programs using grep and sed. Display the lines containing director. Delete those lines whose employ id is two thousand. Count the lines containing manager as designation. Display the line number record having sales as Department. Display the lines where salary lies between 80000-89999. Replace the manager with executive. Replace pipe symbol with colon symbol in the emp.lst. Add prefix e to all employ ids. Grep: UNIX has a special family of commands for handling search requirements, and grep is the principal member of this family. It scans a file for the occurrence of a pattern and, depending on the options used, display Lines containing the selected pattern. Lines not containing the selected pattern (-v). Lines number where the pattern occurs (-n). Number of lines containing the pattern (-c). Filenames where the pattern occurs (-l).

Grep is exceedingly simple to use too. Its syntax treats the first argument as the pattern and the rest as filenames.

Syntax: grep options pattern filename(s)

Sed: -

Sed is a multipurpose tool which combines the work of several filters. Sed is designed by Lee McMahon. Sed is derived from the ed line editor, the original editor of UNIX. Sed is used for noninteractive operations. It acts on data stream.

Sed has very few options. It has numerous features almost bordering on a programming language. Due to obvious constraints, we shall have to stop of its limits because its functions have been taken over by perl. Perl often handle them better and faster. Everything in sed is an instruction. An instruction combines an address for selecting lines with an action to be taken on them.

Syntax:
sed options address action file(s) The address and action are enclosed within single quotes. The action component is drawn from sed family of internal command. It can either be a simple display or an editing function like insertion deletion or substitution of text.

Solution: grep director emp.lst grep -v ^5000 emp.lst > emp2.lst grep -n manager emp.lst grep -c sales emp.lst grep 8.$ emp.lst sed s/manager/executive/ emp.lst sed s/|/:/g emp.lst sed s/^/e/ emp.lst

PRACTICAL N0. 6
AIM: - Develop advanced shell programs using awk.
First, we create a table including empid, name, designation, department and basic pay.

Awk :- It is similar to find and sed. The awk command combines the functions of grep and sed, making it one of the most powerful Unix commands. Using awk, you can substitute words from an input file's lines for words in a template or perform calculations on numbers within a file. The command uses the following syntax : awk options selection_criteraia (action) filename(s) The selection_criteria filters input and selects lines. { print } = whitespace permitted. { print $0} = $0 is the complete lines. Programs :A). Display name, designation of all employees belonging to marketing department. B). Write a program to count manager drawing salary exceeding 7000. C). Write a program to calculate average basic pay of the employees having salary greater than 8000.

D). Write program to calculate average basic pay , average hra, average da and total salary of the employees belonging to sales or marketing department. emp.awk :BEGIN { printf "\t\tEmployee abstract\n\n" } $5 > 7500 { kount++ ; tot+= $5 printf "%3d %-20s %-12s %d\n", kount,$2,$3,$5 } END { printf "\n\tThe average basic pay is %6d\n", tot/kount }

Emp2.awk :-

BEGIN { FS = "|" printf "%42s\n", "Basic Da Hra Gross" } /sales|marketing/ { da = 0.25*$5 ; hra = 0.50*$5 ; gp = $5+hra+da tot[1] += $5 ; tot[2] += da ; tot[3] += hra ; tot[4] += gp kount++ } END { printf "\t Average %5d %5d %5d %5d\n", \ tot[1]/kount, tot[2]/kount, tot[3]/kount, tot[4]/kount }

PRACTICAL NO. 7
AIM- Compile and debug various C programs using different options. GCC
The GNU Compiler Collection (GCC) is by far the most dominant compiler (rather, the most dominant collection of compilers) used on Linux systems. It compiles programs written in C, C++,Objective-C, Fortran, Java, and Ada. GCC gives programmers extensive control over the compilation process. That process includes up to four stages: preprocessing, compilation, assembly, and linking. You can stop the process after any of these stages to examine the compilers output at that stage. GCC can also handle the various C dialects, such as ANSI C or traditional (Kernighan and Ritchie) C. You can control the amount and type of debugging information, if any, to embed in the resulting binary. And as with

most compilers, GCC also performs code optimization. The gcc command invokes the C compiler. To use it, provide it the name of a C source file and use its -o option to specify the name of the output file. gcc will preprocess, compile, assemble, and link the program, generating an executable, often called a binary.

Syntax: gcc infile.c [-o outfile] infile.c is a C source code file and -o says to name the output file outfile. The [] characters indicate optional arguments. If the name of the output file is not specified, gcc names the output file a.out by default. Not all steps need to be handled by the gcc program itself, as gcc can hand off processing tasks such as linking to ld, the GNU linker. Compile program with gcc: $ gcc ulp7 $ ./a.out $ gcc o ulp7 ulp7.c $ ./ulp7 Warnings: $ gcc Wall o ulp7 ulp7.c $ gcc Wall -Werror o ulp7 ulp7.c Optimization with gcc: $ time ./ulp7 $ gcc Wall O1 o ulp7 ulp7.c $ time ./ulp7 Debugging with gcc: $ gcc g Wall o ulp7 ulp.c $gcc ggdb3 Wall o ulp7 ulp7.c
$ gdb ulp7 (gdb)break main (gdb)run (gdb)step (gdb)quit

PRACTICAL NO. 8 Aim: - Create a simple make file and smarter make file.
GNU Make: As your programs get larger, the process necessary to build them becomes more complex and time-consuming. The Linux environment provides a tool to help you with this process: GNU make. A Makefile is nothing more than a collection of rules. A rule consists of following things: Target : - The thing make ultimately tries to create Dependencies: - A list of one or more dependencies (usually files) required to build the target Commands: - A list of commands to execute to create the target from the specified dependencies Dependencies arent necessarily the files that are built. They can be other arbitrary files. For instance, a C program might list an include file as a dependency. This means that if the include file is updated, the C file will be recompiled to take into account the changes Smarter makefile: - You can use variables in your Smarter Makefile. This not only reduces the typing (and possible errors) necessary to create your rules, but also enables you to change the rules throughout the entire file by modifying one or two lines. This can be a big win for large files. Setting variables in a Makefile is similar to doing the same in Bash; you use the equals sign (=) to separate the variable name, on the left, from the new value on the right. To access the contents of the variable later, the syntax is slightly different. With make, you use $(VARIABLE) to access the contents of the variable named VARIABLE. Intelligent Makefiles that can automatically detect many things about their environment so that you often dont need to tell them even the names of the files that comprise your program! For compute.c, the source is: extern int someglobal; int computer(void) { return 5 * someglobal; } For init.c, the source is: #include <stdio.h>

#include myprogram.h int someglobal = 11; int main(void) { foo(); return 0; } For io.c, the source is: #include <stdio.h> #include myprogram.h int foo(void) { printf(The value is: %d.\n, computer()); return 1; } For the header file, myprogram.h, the source is: int computer(void); int foo(void); Code for makefile: all: myprogram. myprogram: io.o init.o compute.o gcc -o myprogram io.o init.o compute.o compute.o: compute.c gcc -Wall -c -o compute.o compute.c init.o: init.c myprogram.h gcc -Wall -c -o init.o init.c io.o: io.c myprogram.h gcc -Wall -c -o io.o io.c Code for smarter makefile: CC=gcc CFLAGS=-Wall COMPILE=$(CC) $(CFLAGS) c all: myprogram myprogram: io.o init.o compute.o $(CC) -o myprogram io.o init.o compute.o init.o io.o: myprogram.h %.o: %.c $(COMPILE) -o $@ $<

Experiment No: - 9
Aim: - To create a smarter makefile.
Smarter makefile: - You can use variables in your Smarter Makefile. This not only reduces the typing (and possible errors) necessary to create your rules, but also enables you to change the rules throughout the entire file by modifying one or two lines. This can be a big win for large files. Setting variables in a Makefile is similar to doing the same in Bash; you use the equals sign (=) to separate the variable name, on the left, from the new value on the right. To access the contents of the variable later, the syntax is slightly different. With make, you use $(VARIABLE) to access the contents of the variable named VARIABLE. Code for smarter makefile: CC=gcc CFLAGS=-Wall COMPILE=$(CC) $(CFLAGS) c all: myprogram myprogram: io.o init.o compute.o $(CC) -o myprogram io.o init.o compute.o init.o io.o: myprogram.h %.o: %.c $(COMPILE) -o $@ $<

Experiment No: - 10
Aim:- Learning of installation and upgradation of Linux operating system.
Theory: -Installing Linux on a personal computer may not be as difficult as you think. This document explains how to install Linux on a PC, starting at the beginning: choosing a distribution The first step for setting up Linux on a PC is the most time consuming, it is simply to use a run from CD version of all distributions that you are interested in to pick the version you want to install. Once you pick the distributions you want to check out, go to the distribution's Web sites and download the live CD/move ISO image for it. Then, using the method for your CD burning software, burn the ISO image to CDROM. With the CDROM in the drive, reboot the computer and you are now running the Linux version. Once you have selected which distribution(s) you will install, you can go back to that distribution's Web site and download the install version of the distribution, which is most commonly made up of three CDROM ISO images. After these are downloaded, burn the ISO images to CDROM. Delete the images from your hard drive after burning them to CDs. You will then have to decide, before going any further, if you wish to multiboot and keep Windows on the system. If you are going to keep Windows, you will have to run a defragmenting utility on the drive before going any further. Completely cleaning up your hard drive, removing all temp files and defragmenting it before backing up the data is always a good idea, and

backing up your system is recommended before installing a new operating system. Because Microsoft's NTFS is not 100 percent supported, this is even more important if you are running any NT-based version of Windows. If you have chosen to use a "Boxed set" of Linux, there is a set of "DOS" tools on one of the CDs, which will run in Windows and allow you to resize the partition for Windows. If you are using a downloaded version, then you can use the Linux tools during installation, but you may have to completely delete the Windows partition. Getting a trial version of Partition magic will allow you to resize the Windows partition without losing the data. The partition table structure for a multi boot system looks complex, at first, but is actually very simple: The first primary partition is your Windows partition. The first extended partition is a transfer partition for enabling read/write access to files from all operating systems, and needs to be either a FAT32 partition or a FAT16 partition The second extended partition is the first Linux partition, and should be set up in the Linux installation process. For only Windows and one Linux version, a 500MB partition is more than enough room. It will be given the label of /boot [500MB in size ] You will need to create a partition with the label / [5 GB in size] Create a partition with the label /home [remaining amount of space for distribution] Create a partition with the label /usr [5 GB in size] Create a partition with the label /var [1 or 2 GB in size] Create a partition with the label /swap [double your RAM in size] When creating the partitions you will notice that you have a number of file system type options; the oldest one being the ext2fs. In a graphic installer, the file system types usually have an explanation of what they mean. The current default file system is the reiserfs, a journaled file system. This has a small hit on speed, but a major improvement on data protection, compared to a non journaled file system. Speed and reliability for data input/output being important, the reiserfs or the ext3fs are the best supported file systems. If speed is more important than reliability, use the ext2fs. This does not mean major risk of data loss, but power fluctuations may cause some data loss or corruption, if you have spotty power, and do not have an interruptible power supply, go with a journalized file system. Follow the prompts for the distribution you are installing. Each distribution has a different installation process, so detailing them here is not a viable option. If you are using one with a console /text interface, the space bar selects, and the right arrow will expand a category, the left arrow will collapse a category, up and down arrows will move you up and down in the listing. The enter key will finish the selection process and start the installation. A graphic interface installation program will have mouse support. Selecting a package

Package selection is a big part of installing Linux. When first trying Linux it doesn't hurt to install everything, as this enables you to see which applications you like and will use. There are far more options than the live CD versions can include, so while you have some idea about packages from having looked at the live CD, there are more options than those shown. Generally, there are over 10 thousand packages in a three CD version of a distribution, including the libraries for software development. You may see a message screen after you have selected, or during the selection process, that lists a number of packages. This is a list of packages required by the one you just selected, called dependencies; you can just hit the ok button when you see it. Some installers allow for this notification to be turned off, which I would recommend against, as the dependencies will help you to see the different parts of each application. During the installation you will be presented with a series of configuration options. The four most important ones are: The firewall--you should turn it on, and at this time you can choose what traffic will be allowed incoming from the Internet, if any. The Display settings--this will configure the graphic server for the GUI, and you should use the test configuration option when doing this. The mouse--it is a good idea to specify which connection and type, as the any USB or PS2 default of many distributions is not always a reliable mouse driver. The Internet connection--if you connect through a network card, then configure it as a network connection, not a DSL connection, even if you use DSL. If you tell Linux it's a DSL connection then Linux looks for the DSL modem as a device in the computer and you will not get online. If you use dial up connection, and your modem is classed as a Winmodem, then you will need to get the drivers for it from the linmodems Web site before installing Linux. After installing Linux, you will have to compile the drivers for the modem, install them and run the network configuration tool for the distribution you have installed. Boot loader When the boot loader is installing, you have the option of setting which boot loader to use, GRUB or LILO, either is a stable option. You can also set which OS will be the default OS at boot. The screens will have a default box on them, if you wish to keep Windows as default then just select default when highlighting Windows (note, it may be DOS with some distributions). You can, if you want, delete the failsafe and nonframebuffer boot options, keeping only Linux, Windows and floppy options. (Note, the floppy option is not always included with newer distributions). If you are installing several versions of Linux, the boot partition created during the first Linux installation will need to be selected and labelled as /boot for each one. Make the same partitions for each version, except for swap, that you only need one. Do NOT use any other pre-existing Linux partition with different distributions, as the versions of software between the

distros may cause conflicts when booting into them. By using the same boot partition, the bootloader installation step will read the data in it and configure the multi-boot for each new distribution. It may be useful to label each distro by its name in the boot menu as you go, this will make the boot options clearer when you are choosing one. When updating the Red Hat EL or SLES operating system on nodes, if the Mode attribute is PreManaged, then after the operating system upgrade, the Mode attribute value is changed to Managed. If the Mode attribute is Managed, then it is not changed. If the Mode attribute is MinManaged before the operating system upgrade, then the Mode attribute value remains MinManaged. If the installnode command fails for a PreManaged node, the attribute value of the node is PreManaged or Installing. If the installnode command fails for a MinManaged node, the attribute value of the node is MinManaged or MinManaged-Installing. To upgrade the operating system and CSM on all the nodes, issue the following command: installnode -a The Red Hat EL nodes with the InstallMethod attribute set to kickstartupgrade are rebooted and upgraded with the new level of the operating system, rebooted, and then CSM is updated if necessary. The Red Hat EL operating system upgrade runs asynchronously. Immediately after the operating system upgrade process is initiated (that is, when the node is rebooted), the installnode command exits, even though the operating system upgrade is not complete. The SLES nodes with the InstallMethod attribute set to you are updated with the new level of the operating system, rebooted to pick up the new kernel, and then CSM is upgraded if necessary. The installnode command continues to run as the SLES operating system is updated. This may take a while to run. Then, installnode reboots the node, and exits. The rest of the upgrade process (CFM, SMS, osupgradepostreboot scripts, upgrading CSM) continues asynchronously. You can use the -t flag on the installnode command to provide a timeout value in minutes. If you do not specify a value for timeout, the default is 60 minutes: installnode -P -t timeout If the operating system upgrade process does not complete within the timeout period specified, CSM considers the operating system upgrade process as failed. You can use the monitorinstall command to provide output information for the installation process. After the operating system is updated, the following jobs run on the node: 1. The osupgradeprereboot customization scripts are run. 2. The node reboots to its local hard disk. 3. CSM is installed, along with the software listed in Planning for CSM for Linux.

4. The node's Mode attribute changes to Managed, or remains MinManaged. 5. SSH or RSH are set up on the node so that the node is accessible from the management server. 6. Any CFM files are transferred to the node. 7. SMS is run to install or update software, if it is configured. 8. The osupgradepostreboot customization scripts are run. If you defined Kerberos options with the csmconfig command when you defined the management server, the installnode command sets up the Kerberos options for the cluster.. After an operating system upgrade the node BIOS boot order can remain: 1. diskette 2. CD-ROM 3. network 4. hard disk Every time the node boots, it uses Dynamic Host Configuration Protocol (DHCP) to contact the management server or install server, which uses pxelinux to boot the node from its hard drive. Alternately, after the operating system upgrade is complete, you can change the boot order in the BIOS to the following: 1. diskette 2. CD-ROM 3. hard disk 4. network

Vous aimerez peut-être aussi