Linux Programming Guide 1 -- Linux_Programming_base.ppt

为给组内兄弟们扫盲,从网上整理的一些东东,与大家一起交流学习。

 

1. Linux_Programming_base.ppt

http://download.youkuaiyun.com/source/1360599

 

 

Linux Programming

www.rt-ics.com

Topics

±    shell command & shell script

±    vi

±    gcc

±    make & makefile

±    gdb

±    pthread (thread , mutex, condition variable)

Linux Programming
 
Command Line

Linux: The Command Line

±         Accessing Linux through a terminal

®        telnet
®        ssh
®        Client :Putty , SecureCRT , SSH Secure Shell

±         Show who is logged in

®        w or who
®        finger

±         Exit from your login session.

®        % exit

®        % logout

®        CTRL-D

Linux: help--man

±    man eg: man gcc

±     Contains info about almost everything :-)

®      other commands

®      system calls

®      c/library functions

®      other utils, applications, configuration files

±     To read about man itself type:
% man man

±     Try:
% man woman ...

Linux: help--apropos

±     Search man pages for a substring.

±     % apropos word

±     Equivalent:

±     % man -k word

Linux: help--info

±    A few commands (such as diff, gcc, awk) are doccumented using info.

®      info is GNU-specific

±    --help , eg: gcc --help

±    Most commands have HTML references on the WWW. 

±    QNX 632.chm

which

±     Displays a path name of a command.

±     Searches a path environmental variable for the command and displays the absolute path.

±     To find which tcsh and bash are actually in use, type:
% which tcsh
% which bash

±     % man which for more details

whereis

±    Display all locations of a command (or some other binary, man page, or a source file).

±    Searchers all directories to find commands that match whereis’ argument

±    % whereis tcsh

chsh

±      Change Login Shell

±      Login shell is the shell that interprets commands after you logged in by default.

±      You can change it with chsh (provided that your system admin allowed you to do so).

±      To list all possible shells, depending on implementation:
% chsh -l
% cat /etc/shells

±      % chsh with no arguments will prompt you for the shell.

passwd

±      Change your login password.

±      A very good idea after you got a new one.

±      It’s usually a paranoid program asking your password to have at least 6 chars in the password, at least two alphabetical and one numerical characters. Some other restrictions (e.g. dictionary words or previous password similarity) may apply.

±      Depending on a privilege, one can change user’s and group passwords as well as real name, login shell, etc.

±      % man passwd

date

±    Guess what :-)

±    Displays dates in various formats

±    % date

±    % date -u

®       in GMT

±    % man date

cal  

±     Calendar

®      for month

®      entire year

±     Years range: 1 - 9999

±     No year 0

±     Calendar was corrected in 1752 - removed 11 days

clear

±    Clears the screen

±    There’s an alias for it: Ctrl+L

±    Example sequence:

®      % cal

®      % clear

®      % cal

®      Ctrl+L

sleep

±    “Sleeping” is doing nothing for some time.

±    Usually used for delays in shell scripts.

±    % sleep 2    2 seconds pause

Command Grouping

±    Semicolon: “;”

±    Often grouping acts as if it were a single command, so an output of different commands can be redirected to a file:

±    % (date; cal; date) > out.txt

alias

±    Defined a new name for a command

±    % alias

®      with no arguments lists currently active aliases

±    % alias newcommand oldcommand

®      defines a newcommand

±    % alias cl cal 2003

±    % cl

unalias

±    Removes alias

±    Requires an argument.

±    % unalias cl

history

±      Display a history of recently used commands

±      % history

®       all commands in the history

±      % history 10

®       last 10

±      % history -r 10

®       reverse order

±      % !!

®       repeat last command

shutdown

±    Causes system to shutdown or reboot cleanly.

±    May require superuser privileges

±    % shutdown -h now      - stop

±    % shutdown -r now      - reboot

 

ls

±      List directory contents

±      Has whole bunch of options, see man ls for details.

±      % ls

®       all files except those starting with a “.”

±      % ls -a

®       all

±      % ls -A

®       all without “.” and “..”

cat

±      Display and concatenate files.

±      % cat

®       Will read from STDIN and print to STDOT every line you enter.

±      % cat file1 [file2] ...

®       Will concatenate all files in one and print them to STDOUT

±      % cat > filename

®       Will take whatever you type from STDIN and will put it into the file filename

±      To exit cat or cat > filename type Ctrl+D to indicate EOF (End of File).

more / less

±    Pagers to display contents of large files page by page or scroll line by line up and down.

±    Have a lot of viewing options and search capability.

±    Interactive. To exit: ‘q’

 

less

±      less ("less is more") a bit more smart than the more command

±      to display contents of a file:

®       % less filename

±      To display line numbers:

®       % less -N filename

±      To display a prompt:

®       % less -P"Press 'q' to quit" filename

±      Combine the two:

®       % less -NP"Blah-blah-blah" filename

±      For more information:

®       % man less

touch

±    By touching a file you either create it if it did not exists (with 0 length).

±    Or you update it’s last modification and access times.

±    There are options to override the default behavior.

±    % touch file

±    % man touch

cp

±     Copies files / directories.

±     % cp [options] <source> <destination>

±     % cp file1 file2

±     % cp file1 [file2] /directory

±     Useful option: -i to prevent overwriting existing files and prompt the user to confirm.

mv

±     Moves or renames files/directories.

±     % mv <source> <destination>

®      The <source> gets removed

±     % mv file1 dir/

±     % mv file1 file2

®      rename

±     % mv file1 file2 dir/

±     % mv dir1 dir2

rm

±    Removes file(s) and/or directories.

±     % rm file1 [file2] ...

±     % rm -r dir1 [dir2] ...

±     % rm -r file1 dir1 dir2 file4 ...

script

±     Writes a log (a typescript) of whatever happened in the terminal to a file.

±     % script [file]

±     % script

®      all log is saved into a file named typescript

±     % script file

®      all log is saved into a file named file

±     To exit logging, type:

®      % exit

find

±      Looks up a file in a directory tree.

±      % find . -name name

±      % find . /(-name w* -or -name W* /)

mkdir

±    Creates a directory.

±    % mkdir newdir

±    Often people make an alias of md for it.

cd

±    Changes your current directory to a new one.

±    % cd /some/other/dir

®      Absolute path

±    % cd subdir

®      Assuming subdir is in the current directory.

±    % cd

®      Returns you to your home directory.

pwd

±    Displays personal working directory, i.e. your current directory.

±    % pwd

rmdir

±    Removes a directory.

±    % rmdir dirname

±    Equivalent:

®      % rm -r dirname

ln

±    Symbolic link or a “shortcut” in M$ terminology.

±     % ln s <real-name> <fake-name>

chmod

±     Changes file permissions

±     Possible invocations

®      % chmod 600 filename

®      -rw------- 1 user group 2785 Feb 8 14:18 filename
(a bit not intuitive where 600 comes from)

®      % chmod u+rw filename
(the same thing, more readable)

®      For the assignment:

®       % chmod u+x myshellscript
(mysshellscript is now executable)
®       -rwx------ 1 user group 2785 Feb 8 14:18 myshellscript

Pipes

±     What's a pipe?

®      is a method of interprocess communication (IPC)

®      in shells a '|' symbol used

®      it means that the output of one program (on one side of a pipe) serves as an input for the program on another end.

®      a set of "piped" commands is often called a pipeline

±     Why it's useful?

®      Because by combining simple OS utilities one can easily solve more complex tasks

Pipes and Redirections

±    |

±   

±   

±    >> 

±    << 

Commands

±        chmod

±        pwd

±        ls

ls file; ls directory ;  ; ls –a ; ls –l ; ls -R

±        cd

±        mkdir

±        rmdir

±        mv

mv oldfilename newfilename

mv file1 file2 file3 newtargetdirectory

±        cp       -- syntax like mv

±        rm

±        find

±        echo

±        cat

±        Whereis

±        printenv,env,set,export

±        grep

Linux commands for programmers

®       man –k                    Search man pages by topic

®       time                 How long your program took to run

®       date                 print out current date/time

®       test                  Compare values, existence of files, etc

®       tee                   Replicate output to one or more files

®       diff                   Report differences between two files

®       sdiff                  Report differences side-by-side

®       wc                   Show number of lines, words in a file

®       sort                  Sort a file line by line

®       gzip                 Compress a file

®       gunzip                     Uncompress it

®       strings                     Print out ASCII strings from a (binary)

®       ldd                   Show DLLs/SOs program is linked to

®       nm                   Show detailed info about a binary obj

 

Linux Shell Scripting: Conditional Execution

±     program1 && program2

®      Program 2 will execute if and only if program1 exited with a 0 status

®      Example:

®      project1 && echo “Project1 Finished correctly!”

±     program1 || program2

®      Program 2 will execute if and only if program1 exited with a non-0 status

®      Example:

®      project1 || echo “Project1 FAILED to complete!”

±     Exit a script with an error:

®      exit 1

Linux job control

±       Start a background process:

®        program1 &

®        program1

        Hit CTRL-Z

        bg

±       Where did it go?

®        jobs

®        ps

±       Terminate the job: kill it

®        kill %jobid

®        kill pid

±       Bring it back into the foreground

®        fg %1

±       Start a job in the future

®        at

Regular Expressions

±    Powerful language for specifying strings of text to be searched and/or manipulated.

±    Used by

®        grep    “Get Regular Expression and Print” – search files line by line

®        sed     Simple Editing tool, right from the command line

®        awk     Scripting language, executes “program” on matching lines

®        perl     Pathological Rubbish Lister. Powerful programming language

±     Note: These are not “file-globs”. The syntax is similar, but the semantics are slightly different!

±     Cannot be used to match nested structures

Regular Expressions: Summary

±        Fundamentals:

Match the specified character unless it is a ...

        .                     Match any character (except EOL)

        [character class]        Match the characters in character class.

           [start-end]              start to end

           [^character class]    Match anything except the character class.

        $                    Match the end of the line

        ^                     Match the beginning of the line

        *                    Match the preceeding expression zero or

                             more times

        ?                    Match the preceeding zero or one time

        |                     Match the lef hand side OR the right side

        (regexp)          Group the regular expression

        /                     Treat next character literally (not specially)

±        Examples:

        Match a line beginning with a space-padded line number and colon.

           ^[ /t]*[0-9][0-9]*:

        Match my name (various spellings)

           (Tim Shelling)|(TJS)|(T/. Shelling)|(Timothy J/. Shelling)

        Match if the line ends in a vowel or a number:

           [0-9aeiou]$

        Match if the line begins with anything but a vowel or a number:

           ^[^0-9aeiou]

 

Searching for Text Using the grep Command

±    The grep command prints matching patterns in a file

±    General syntax:

®      grep options pattern filename

±    Useful option is i for ignoring the case you are matching

±    Uses regular expressions for pattern matching

 

 

grep

±      Searches its input for a pattern.

±      The pattern can be a simple substring or a complex regular expression.

±      If a line matches, it’s directed to STDOUT; otherwise, it’s discarded.

±      % echo blah-foo | grep blah

®       Will print the matching line

±      % echo blah-foo | grep zee

®       Will not.

Searching for Text Using the grep Command

Understanding Signals

±      Shell uses signals to control processing of jobs

±      Signal is message sent to a process

±      Use the kill command to send a signal to a process

±      Example to sent signal 9 to process ID 1002

®       kill –9 1002

±      Use the trap command to capture a signal

±      Example:

®       trap “echo Caught [Ctrl]+C” 2

 

Understanding Signals

Linux Shell Script
Programming Concepts

Understanding the Basic Components of a Shell Script

±    Specifying the command interpreter

®      Different shells with different syntax

®      Use #!shell-path on the first line

±    Comments

®      To help understand the program

®      Use # to signify a comment

®      Can be anywhere in the script

 

Shell Commands

±     Shell commands are interpreted directly by the shell you specify.

±     The commands are similar to the statement in some programming languages, such as C.

±     Popular shells include:

®      Enhanced C-shell tchs (csh+)

®      Bourne-Again Shell, bash (sh+)

®      Korn Shell (ksh)

±     These notes will focus on the first two shells.

Shells’ Features

±     The bash an tcsh shells are similar in the features the offer. In particular:

®      Pass arguments to your script

®      Set and reference variables

®      Use of control flow

®      Interact with the user (read user input)

®      Comments…

±     Info on commands a given shell offers can be found in the man pages for that shell.

±     There are many Linux/UNIX references that give detailed information and tips.

Shell Scripts

±    What are they for?

®      To automate certain common activities an user performs routinely.

®      They serve the same purpose as batch files in DOS/Windows.

®      Example:

®      rename 1000 files from upper case to lowercase

What are Shell Scripts

±     Just text/ASCII files with:

®      a set of standard UNIX/Linux commands (ls, mv, cp, less, cat, etc.) along with

®       flow of control
®       some conditional logic and branching (if-then),
®       loop structures (foreach, for, while), and
®       I/O facilities (echo, print, set, ...).

®      They allow use of variables.

®      They are interpreted by a shell directly.

®      Some of them (csh, tcsh) share some of C syntax.

®      DOS/Win equivalent - batch files (.bat)

Why not use C/C++ for that?

±    C/C++ programming requires compilation and linkage, maybe libraries, which may not be available (production servers).

±    For the typical tasks much faster in development, debugging, and maintenance (because they are interpreted and do not require compilation).

Shell Script Invocation

±      Specify the shell directly:

®       % tcsh myshellscript

®       % tcsh -v myshellscript
(-v = verbose, useful for debugging)

±      Make the shell an executable first and then run is a command (set up an execution permission):

®       % chmod u+x myshellscript

±      Then either this:

®       % myshellscript
(if the path variable has ‘.’ in it; security issue!)

±      Or:

®       % ./myshellscript
(should always work)

Shell Script Invocation (2)

±     If you get an error:
“myshellscrip: command not found”

®      The probably “.” is not in your path or there’s no execution bit set.

±     When writing scripts, choose unique names, that preferably do not match system commands.

®      Bad name would be test for example, since there are many shells with this internal command.

±     To disambiguate, always precede the shell with “./” or absolute path in case you have to name your thing not very creatively.

Start Writing a Shell Script

±     The very first line, often called 'shebang' (#!) should precede any other line, to assure that the right shell is invoked.

 

 

 

 

±     Comments start with '#', with the exception of #!, $#, which are a special character sequences.

±     Everything on a line after # is ignored if # is not a part of a quoted string or a special character sequence.

Understanding the Basic Components of a Shell Script

Understanding the Basic Components of a Shell Script

±    Variables

®      Represent data

®      Variable declaration at the beginning of your script or prior to using them

®      Use the declare or typeset command

®      Initialization sets a variable to a beginning value

®      Useful for guaranteeing a variables contents
®      Example: NetPay=0

 

Understanding Parameters

±    Positional

®      Can pass data to scripts

®      Use numbers 0 through 9 when referencing

®      $0 is the script itself

®      $1 through $9 represent data

®      Use the shift command to pass more than 9 variables to a script

Understanding Parameters

 

 

Understanding Parameters

Understanding Parameters

Understanding Parameters

Understanding Parameters

±    Special parameters

®      Preceded with a dollar sign ($)

®      Examples

®      @  expands into all of the positional parameters
®      # expands to the number of positional parameters
®      ? expands to the exit status of the previous command
®      $ expands to the shells PID
®      ! expands to the PID of the previous background process

Linux: Bourne Shell script syntax

±       The first line of a sh script must start as follows:

#!/bin/sh

±       # is treated as the beginning of a comment until end-of-line

±       Every line is first parsed for shell metacharacters. These include characters that the shell will do something with and include:

# ‘ “ & > < $ % * [ ] ? ! ` ~ ; | ,  { }

±       Distinct commands may be separated by end-of-line, semicolon(;), or comma(,)

±       Environment variables are $EXPANDED

±       “Back-tick” subshells are executed and `expanded`

±       Pipelines are created | joining the output of | one program | with the next

±       Any commands left over must be builtins or external commands.

±       An error will fail the pipeline, but the script will continue!

Understanding Parameters

±    Using a Usage Clause

®     A statement about the scripts use

®     Typically used with positional parameters

®      Use $# for testing the proper number of positional parameters

Understanding Parameters

Creating Interactive Scripts

±    Use the read command to prompt for user input

±    The read command options

®      -p prompt used to display a prompt

®      -s used to suppress characters entered

®      -t timeout used to expire the command once the timeout seconds value has been reached

®      -a array-name used to read data into an array

 

Creating Interactive Scripts

Creating Interactive Scripts

±    You can protect a variable to ensure the contents do not change

±    Use the readonly command

±    Example:

®      readonly Zip

Creating Interactive Scripts

tcsh
Quick Ref

Variables

±      Variables start with a $ sign when they are used.

®       $x, $val

±       There's no $ when a variable is declared.

®       set x = 3

®       @ y = 1

®       set input = "$<"

±      There are some system, predefined variables:

®       $0, $1, $3 .... - argument references (arguments themselves)

®       $* - all the arguments

®       $< - user's input from STDIN

®       $# - # of arguments passed to the script

if

if ( <expression> ) then

    <statements>

else if ( <another-expression> ) then

    <statements>

else

    <statements>

endif

 

foreach

foreach var ( <list-of-values> )

   <statements>

end

switch

switch ( string )

case str1:

   <statements>

   breaksw

...

default:

   <statements>

   breaksw

endsw

while

while ( <expression> )

   <statements>

end

 

Example

Bourne Shell
Quick Ref

Quick Resource Summary

±    Manual Pages:

man bash

±    An Intro to UNIX Shell:

<http://steve-parker.org/sh/bourne.html>

±    How To Write a Shell Script:

<http://www.tinker.ncsu.edu/LEGO/shell_help.html>

Bourne Shell Script Constructs Reference

±    System/Internal Variables

±    Control Flow (if, for, case)

 

Internal Variables

Internal Variables (2)

±     Use shift command to shift the arguments one left:

®      Assume intput:

®       ./shift.sh 1 2 foo bar
®       $0 = <directory-of>/shift.sh
®       $1 = 1
®       $3 = 2
®       $4 = foo
®       $5 = bar
®       shift:
®       $1 = 2
®       $2 = foo
®       $3 = bar

Environment

±     These (and very many others) are available to your shell:

®      $PATH - set of directories to look for commands

®      $HOME - home directory

®      $MAIL

®      $PWD – personal working directory

®      $PS1 – primary prompt

®      $PS2 – input prompt

®      $IFS - what to treat as blanks

Control Flow: if

±    General Syntax:

 

 

 

 

±    <expression> can either be a logical expression or a command and usually a combo of both.

if (2)

±     Some Logical “Operators”:

-eq --- Equal

-ne --- Not equal

-lt --- Less Than

-gt --- Greater Than

-o   --- OR

-a   --- AND

±     File or directory?

-f   --- file

-d   --- directory

case

±    Syntax:

 

case (2)

case $# in

    1) cat >> $1

       ;;

    2) cat >>$2 <$1

       ;;

    3) case $3 in

           -[abc]) echo "-a -b or -c"

                   ;;

        -foo|-bar) echo "-foo or -bar"

                   ;;

       esac

       ;;

    *) echo "we accept up to 3 args only."; exit 127

       ;;

esac

for

±    Syntax:

 

 

 

 

±    List can also be a result of a command.

for (3)

for file in *.txt

do

    echo File $file:

    echo "======"

    cat $file

    echo "======"

done

while

±    Syntax

until

±    Syntax

 

Example

±    bash example

Linux Programming
 
vi

命令到编辑

±    a:光在下一字符处开编辑

±    A:光到行尾编辑

±    i:光前位置编辑

±    I:光到行首编辑 

±    o:在下一行始一新行编辑

±    O:在上一行始一新行编辑

 

从编辑到命令

±    ESC

文件

±    q       

±    :q!      强制离

±    :e xxxx    编辑xxxx

±    :w       保存

±    :w xxxx    另存xxxx

±    :w!      强制保存

±    :wq          保存离

cursor

±    h,j,k,l       往左,往下,往上,往右

±    0        到行首,注意里是0,不是字母o

±    $        到行尾

±    ^         到本行的第一個非空白字元

 

cursor

±    w,W        到下個字, 到下個非空白的字

±    b,B     回上個字, 到上個非空白的字

±    e,E          到這個字的字尾, 到下個非空白的字字尾

 

cursor

±    Ctrl-F ,Ctrl-B     往後一頁,往前一頁

±    G        到檔尾

±    :n       到第n行 (所以到檔頭就是:1)

±    Ctrl-G      顯示第幾行

±    J        兩行

 

搜尋與取代

±       /

±       /pattern    尋找pattern

±       ?pattern        往上尋找pattern

±       n              再往下尋找

±       N             再往上尋找

±       :s/patrn/str/cgi搜尋patrn取代str

±                       其中:s間必需指定範圍(range)沒設範圍就是游標這行

±                       1,10 表示 1-10

±                       %    表示整篇

±                       最後cgi

±                       c 表示confirm尋問

±                       g 表示global全部

±                       i 表示ignore不分大小寫

 

常用字元字串處理

±     cc        改變整行

±     dd        掉整行

±     yy         拷貝整行(yank whole line)

±     p,P      貼上(paste) 最近掉或拷貝的

±     cw        改變一個字

±     d$        到行尾

±     ye        拷貝到這個字尾

±     r,R       取代一個字元, 取代整行

±     u,U       undo 最後修改,UNCHANGE整行

±     x,X       一個字元, 往回個字元(等於按backspace)

重複的處理

±    .         重複剛剛的命令或輸入

 

indentation

±    >>      往右一個indent

±    <<      往左一個indent

 

vim的多檔與多窗

±     :e xxx          編輯xxx

±     :buffers        列出所有編輯檔

±     :bn             n是數 b1 b2 b3....表是開第nbuffer

±     :bdn            n是數:bd1 :bd2 表示殺掉第nbuffer

±     :new          一個水平新窗

±     :vnew        開個垂直新窗

±     :only           只留一個窗窗

±     C-w j k h l     移到下 窗去

:set [all]

±    Sets some customizing options to VI and EX.

±    The ":set all" command gives all the possible options.

±    :set tabstop=8

±    :set number

±    :set nonumber

 

Linux Programming
 
gcc

Contents

±    Intro

±    Options

±    Examples

What is gcc?

±      gcc

®       stands for GNU C/C++ Compiler

®       a popular console-based compiler for *NIX platforms and others; can cross-compile code for various architectures

®       gcc to compile C programs; g++ for C++

®       can actually work with also ADA, Java, and a couple other languages

®       gcc performs all of these:

®        preprocessing,
®        compilation,
®        assembly, and
®        linking

±      man gcc

±      QNX632.chm

 

Options

±     To compile: -c

±     Specify output filename: -o <filename>

±     Include debugging symbols: -g

±     GDB friendly output: -ggdb

±     Show all (most) warnings: -Wall

±     Be stubborn about standards: -ansi and -pedantic

±     Optimizations: -O, -O*

Options: -c

±    gcc performs compilation and assembly of the source file without linking.

±    The output are usually object code files, .o; they can later be linked and form the desired executables.

±    Generates one object file per source file keeping the same prefix (before .) of the filename.

Options: -o <filename>

±     Places resulting file into the filename specified instead of the default one.

±     Can be used with any generated files (object, executables, assembly, etc.)

±     If you have the file called source.c; the defaults are:

®      source.o if -c was specified

®      a.out if executable

±     These can be overridden with the -o option.

Options: -g

±    Includes debugging info in the generated object code. This info can later be used in gdb.

±    gcc allows to use -g with the optimization turned on (-O) in case there is a need to debug or trace the optimized code.

Options: -ggdb

±    In addition to -g produces the most GDB-friendly output if enabled.

Options: -Wall

±      Shows most of the warnings related to possibly incorrect code.

±      -Wall is a combination of a large common set of the -W options together. These typically include:

®       unused variables

®       possibly uninitialized variables when in use for the first time

®       defaulting return types

®       missing braces and parentheses in certain context that make it ambiguous

®       etc.

±      Always a recommended option to save your bacon from some “hidden” bugs.

±      Try always using it and avoid having those warnings.

Options: -ansi and -pedantic

±     For those who are picky about standard compliance.

±     -ansi ensures the code compiled complies with the ANSI C standard; -pedantic makes it even more strict.

±     These options can be quite annoying for those who don’t know C well since gcc will refuse to compile unkosher C code, which otherwise it has no problems with.

Options: -O, -O1, -O2, -O3, -O0, -Os

±     Various levels of optimization of the code

±     -O1 to -O3 are various degrees of optimization targeted for speed

±     If -O is added, then the code size is considered

±     -O0 means “no optimization”

±     -Os targets generated code size (forces not to use optimizations resulting in bigger code).

Options: -I

±     Tells gcc where to look for include files (.h).

±     Can be any number of these.

±     Usually needed when including headers from various-depth directories in non-standard places without necessity specifying these directories with the .c files themselves, e.g.:
#include “myheader.h” vs.
#include “../foo/bar/myheader.h”

For Your Assignments

±    For your assignments, I’d strongly suggest to always include -Wall and -g.

±    Optionally, you can try to use -ansi and –pedantic, which is a bonus thing towards your grade.

±    Do not use any optimization options.

±    You won’t need probably the rest as well.

Example

±      For example, if you have the following source files in some project of yours:

®       ccountln.h

®       ccountln.c

®       fileops.h

®       fileops.c

®       process.h

®       process.c

®       parser.h

®       parser.c

±      You could compile every C file and then link the objet files generated, or use a single command for the entire thing.

®       This becomes unfriendly when the number of files increases; hence, use Makefiles!

±      NOTE: you don’t NEED to compile .h files explicitly.

Example (2)

±     One by one:

®      gcc -g -Wall -ansi -pedantic -c ccountln.c

®      gcc -g -Wall -ansi -pedantic -c parser.c

®      gcc -g -Wall -ansi -pedantic -c fileops.c

®      gcc -g -Wall -ansi -pedantic -c process.c

±     This will give you four object files that you need to link and produce an executable:

®      gcc ccountln.o parser.o fileops.o process.o -o ccountln

Example (3)

±     You can do this as well:

®       gcc -g -Wall -ansi -pedantic ccountln.c parser.c fileops.c process.c -o ccountln

±     Instead of typing this all on a command line, again: use a Makefile.

Example (4)

Linux Programming
 
makefile

Intro

±    Makefiles in conjunction with the make utility (man make) provide a very convenient facility to build, install, and uninstall large (and small too) projects in the *nix systems.

±    Makefiles are text files and similar in a way to the shell scripts, which are interpreted by the make utility.

Intro (2)

±     A makefile may have some variables declared for convenience then followed by rules on how to build a given target program.

±     The variable part usually declares variables like which compiler to use across all the targets:

®      which compiler options to use,

®      where to look for libraries and include files, etc.

±     The rules specify what's needed to build a specific part and how to do it, using shell commands.

Intro (3)

±   The make utility avoids re-bulding targets which are up-to-date, thus, saving typing and compiling time a lot.

±   Makefiles largely similar to the Project and Workspace files you might be used to from Visual C++, JBuilder, Eclipse, etc.

Make command line (simplified)

make [options] [targets]

 

±    options include

®      “-f filename”     use filename as the Makefile

®      “-n”  don’t do anything – just print what needs to be done.

±    targets are what should be built (if needed).

 

Specifying Targets

±   When making all the stuff in your program typing make is enough.

±   In certain cases, the make utility assumes target “all”, or most often the first target in the list.

±   If you want to build a specific target just supply it as a parameter to make: make mytarget

Filenames

±     When you key in make, the make looks for the default filenames in the current directory. For GNU make these are:

®      GNUMakefile

®      makefile

®      Makefile

±     If there more than one of the above in the current directory, the first one according to the above chosen.

±     It is possible to name the makefile anyway you want, then for make to interpret it:
make -f <your-filename>

Basic Makefile Format

±    Basic Format Summary:

Basic Makefile Format (2)

±    Comments

®      Just like for most shell scripts, they start with ‘#

±    Variables (make calls them macros)

®      Are assigned the same way as in bash:
var=value

®      Used as: $(var)

®      Variables can be scalar as well as lists (‘arrays’)

Rules

±     Rule or several of then are needed to direct compilation and building, installation, and clean up actions that depend on certain prerequisites.

±     Basic components of a Rule are

®      Ultimate target of a rule, the goal

®      List of dependencies needed to be satisfied before this rule can be executed, the prerequisites

®      List of actions, or command, that are executed once all prerequisites satisfied to arrive to the target goal.

Rules

     target : prerequisites

        command1

        command2

       

 

target depends on the files listed after the colon.

commands are unix commands that build a new target file.

Simple Example

±    This rule would tell make that the file linecount depends on the file foo.c.

±    To build linecount the command “wc l foo.c > linecount” should be run.

 

linecount : foo

  wc l foo.c > linecount

Simple Makefile for building a program.

subs.o: subs.c

   gcc c subs.c

 

main.o: main.c

   gcc c main.c

 

main: main.o subs.o

   gcc o main main.o subs.o

Macros

±    You can create macros (fancy variables)

 

OBJS = subs.o main.o

 

main: $(OBJS)

gcc o main $(OBJS)

Fancy Stuff

±    Macro substitution – evaluates to the value of a macro after some substitutions:

 

SOURCE = main.c subs.c

OBJS = ${SOURCE:.c=.o}

 

now OBJS is main.o subs.o

Suffix Rules

±    General rules for building files that end with some suffix from files with the same name but a different suffix.

±    For example, how to build a .o file from a .c file.

±    Special predefined macros help with suffix rules:

$< means current prereq.

$@ is the current target.

Example Suffix Rule

.c.o:

  gcc c $<

 

This rule tells Make how to create a .o file any time is has a .c file (and needs the .o file to build a target).

A Complete Example

.c.o:

  gcc c $<

 

SOURCE = main.c subs.c

OBJS = ${SOURCE:.c=.o}

 

main: $(OBJS)

gcc o main $(OBJS)

Targets

±       Target name can be almost anything:

®        just a name

®        a filename

®        a variable

±       There can be several targets on the same line if they depend on the same things.

±       A target is followed by

®        a colon “:”

®        and then by a list of dependencies, separated by spaced

±       The default target make is looking for is either all or first one in the file.

±       Another common target is clean

®        Developers supply it to clean up their source tree from temporary files, object modules, etc.

®        Typical invocation is:
make clean

±       You are required to supply another target, called run, so that it makes sure your application is compiled and run just by typing:
make run.

Dependencies

±       The list of dependencies can be:

®        Filenames

®        Other target names

®        Variables

±       Separated by a space.

±       May be empty; means “build always”.

±       Before the target is built:

®        it’s checked whether it is up-to-date (in case of files) by comparing time stamp of the target of each dependency; if the target file does not exist, it’s automatically considered “old”.

®        If there are dependencies that are “newer” then the target, then the target is rebuild; else untouched.

®        If you want to “renew” the target without actually editing the dependencies, “touch” them with the touch command.

®        If the dependency is a name of another rule, make descends recursively (may be in parallel) to that rule.

Actions

±     A list of actions represents the needed operations to be carried out to arrive to the rule’s target.

®      May be empty.

±     Every action in a rule is usually a typical shell command you would normally type to do the same thing.

±     Every command MUST be preceded with a tab!

®      This is how make identifies actions as opposed to variable assignments and targets. Do not indent actions with spaces!

Line-Oriented

±     Makefile is a line-oriented file.

±     That means by the end of line a new line starts, it is either a new action or target or whatever.

±     If your list of dependencies or a command are too long and you would like for them to span across several lines for clarity and convenience, you may do so, but you will have to escape the end of line by “/” at the end of each such a line.

±     Make sure not to use tabs for such lines.

More Advanced Constructs

±     List/array variables/macros can be assignment via the “:=” operator.

±     It is possible to use control-flow constructs within the actions part of a rule, such as for, if-then-else, test, etc. The syntax is that of bash.

±     Implicit targets for files of specific extensions.

±     “Macros” and “directives” for conditional variable definitions as well as to include other makefiles.

±     Others...

±     Not part of this “study” yet...

Examples

 

sum: main.o sum.o

     gcc –o sum main.o sum.o

 

main.o: main.c sum.h

     gcc –c main.c

 

sum.o: sum.c sum.h

     gcc –c sum.c

 

Rule syntax

 

main.o: main.c sum.h           

    gcc –c main.c

 

tab

 

     dependency               action

Equivalent makefiles

±    .o depends (by default) on corresponding .c file. Therefore, equivalent makefile is:

 

sum: main.o sum.o

      gcc –o sum main.o sum.o

 

main.o: sum.h

      gcc –c main.c

 

sum.o: sum.h

      gcc –c sum.c

     

Equivalent makefiles - continued

±    We can compress identical dependencies and use built-in macros to get another (shorter) equivalent makefile :

sum: main.o sum.o

     gcc –o $@ main.o sum.o

 

main.o sum.o: sum.h

     gcc –c $*.c

 

 

Another makefile example

# Makefile to compare sorting routines

 

BASE = /home/blufox/base

CC           =   gcc

CFLAGS  =   -O –Wall

EFILE      =   $(BASE)/bin/compare_sorts

INCLS     =   -I$(LOC)/include

LIBS        =   $(LOC)/lib/g_lib.a /

                     $(LOC)/lib/h_lib.a

LOC        =   /usr/local

 

OBJS = main.o    another_qsort.o    chk_order.o /

             compare.o    quicksort.o

 

$(EFILE): $(OBJS)

        @echo “linking …”

        @$(CC) $(CFLAGS) –o $@ $(OBJS) $(LIBS)

 

$(OBJS): compare_sorts.h

        $(CC) $(CFLAGS) $(INCLS) –c $*.c

 

# Clean intermediate files

clean:

        rm *~ $(OBJS)

 

Example - continued

±    We can define multiple targets in a makefile

±    Target clean has an empty set of dependencies. Used to clean intermediate files.

±    make

®      Will create the compare_sorts executable

±    make clean

®      Will remove intermediate files

 

Passing parameters to makefile

±    We can pass parameters to a makefile by specifying them along with their values in the command line.

±    For example:

   make PAR1=1 PAR2=soft1

    will call the makefile with 2 parameters: PAR1 is assigned the value 1 and PAR2 is assigned the value soft1. The same names should be used within the makefile to access these variables (using the usual $(VAR_NAME) syntax)

Passing parameters - continued

±    Note that assigning a value to a variable within the makefile overrides any value passed from the command line.

 

±    For example:

   command line : make PAR=1

    in the makefile:

    PAR = 2

 

±    PAR value within the makefile will be 2, overriding the value sent from the command line

     

Conditional statements

±    Simple conditional statements can be included in a makefile.

±    Usual syntax is:

 

   ifeq (value1, value2)

     body of if

    else

     body of else

    endif

Conditional statements - example

sum: main.o sum.o

        gcc –o sum main.o sum.o

 

main.o: main.c sum.h

        gcc –c main.c

 

#deciding which file to compile to create sum.o

ifeq ($(USE_SUM), 1)

 

sum.o: sum1.c sum.h

        gcc –c sum1.c –o $@

 

else

sum.o: sum2.c sum.h

        gcc –c sum2.c –o $@

 

endif

Linux Programming
 
libgen makefile

R_IL1_0.1/libgen/build/makefile

LIBGEN_DIRS = ${VOBTAG}/libgen/lib/build /

              ${VOBTAG}/libgen/src/dmxmsg/core-mod

              ${VOBTAG}/libgen/src/dmxmsg/octeon-mod /

              ${VOBTAG}/libgen/tst/ste

 

all:

      for d in $(LIBGEN_DIRS); do cd $$d && make;done

      touch build.tag

 

 

clean:

      for d in $(LIBGEN_DIRS); do cd $$d && make clean;done

      touch build.tag

Linux Programming
 
GDB in Chinese

GDB

  GDBGNU开源组织发布的一个强大的UNIX下的程序调试工具。

  Linux下的GNU的调试器称为GDBGNU Debugger)。

  该软件最早由Richard Stallman编写,目前版本version 6.8

  GDB是一个基于命令行工作模式下的程序。

  GDB是一个用来调试CC++程序的调试器。

GDB

   gdb - GNU debugger

   gdb的主要功能 救死扶

     gdb的主要用途 bug;分析程序结构

   gdb官方 - http://www.gnu.org/software/gdb/gdb.html

   gdb地址 - http://ftp.gnu.org/gnu/gdb/

 

 程序的编译

±    1. gcc-g选项决定了可行程序中包含调试信息。

±    2. -O?选项会了程序结构致程序代和可行的二制代系不存在了,所以在GDB调试时不能加入该选项

GDB有三种调试方法:

±     1. 调试新的

±    2. attach并调试经运行的

±     3. 调试机上的新

调试新的

±    1. 用程序名和转储文件作为参数启动GDB

±    2. run行程序,run命令可以上程序的参数

 

调试新的

±        [root@localhost dftp]# gdb dftp

±        GNU gdb 6.8

±        Copyright (C) 2008 Free Software Foundation, Inc.

±        License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

±        This is free software: you are free to change and redistribute it.

±        There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

±        and "show warranty" for details.

±        This GDB was configured as "i686-pc-linux-gnu"...

±        (gdb) run "o 192.168.211.232"

±        Starting program: /hdb/project/dftp/dftp "o 192.168.211.232"

±        dftp: ftp client example

±        Copyright 1996 (c) Donald C. Asonye

±        Email: donald@uh.edu

±        Connecting to 192.168.211.232

±        Connected to 192.168.211.232

±        220 WFTPD 2.0 service (by Texas Imperial Software) ready for new user

±        Login:

attach并调试经运行的

±    1.确定需要调试id

±    2.gdbattach pid

attach并调试经运行的

±        [root@localhost dftp]# ps

±          PID TTY          TIME CMD

±         7857 pts/2    00:00:00 bash

±         8121 pts/2    00:01:07 dftp

±         8196 pts/2    00:00:00 ps

±        [root@localhost dftp]# gdb dftp

±        GNU gdb 6.8

±        Copyright (C) 2008 Free Software Foundation, Inc.

±        License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

±        This is free software: you are free to change and redistribute it.

±        There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

±        and "show warranty" for details.

±        This GDB was configured as "i686-pc-linux-gnu"...

±        (gdb) attach 8121

±        Attaching to program: /hdb/project/dftp/dftp, process 8121

±        Reading symbols from /lib/tls/libc.so.6...done.

±        Loaded symbols for /lib/tls/libc.so.6

±        Reading symbols from /lib/ld-linux.so.2...done.

±        Loaded symbols for /lib/ld-linux.so.2

±        0x007087a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2

±        (gdb)

调试机上新建的

±    1. gdb行在调试机上,gdbserver行在目机上。

±    2. 者之的通信据格式由gdb程串行协议RSPRemote Serial Protocol)

±    3. RSP协议数据的基本格式$#协议数据可以基于串口,TCPUDP实现

 

调试机上新建的

±      Target:

±      Target# gdbserver 192.168.211.233:1208 main

 

±      Host:

±      Host# gdb main

±      (gdb) target remote 192.168.211.234:1208

 

调试机上新建的

看代

±     backtrace

±     backtrace生成致段错误的函数栈信息.

 

±       (gdb) backtrace

±       #0  0x007087a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2

±       #1  0x007e0a1d in ___newselect_nocancel () from /lib/tls/libc.so.6

±       #2  0x08049add in CheckFds (command=0xbfeee410 "") at scon.c:690

±       #3  0x0804a9d3 in Interact () at main.c:52

±       #4  0x0804abfb in main (argc=1, argv=0xbfeee8d4) at main.c:156

±       (gdb)

看代

±     list

±     list打印程序源代

 

±     list <linenum>

±     示程序第linenum行的周的源程序。

±     list <function>

±     示函function的函的源程序。

±     list

±     前行后面的源程序。

±     list -

±     前行前面的源程序。

检查数

±    print

±    print可以示被调试程序中的表式,量和据的

±    打印i

±    (gdb) print i

±    打印ary始的10个内

±    print ary@10

±    打印ary始的10个值

±    print ary[0]@10

 

 

输出格式

±      x 按十六制格式量。

±      d 按十制格式量。

±      u 按十六制格式示无符整型。

±      o 按八制格式量。

±      t 按二制格式量。

±      a 按十六制格式量。

±      c 按字符格式量。

±      f 按浮点格式量。

±      (gdb) p i

±      $21 = 101

±      (gdb) p/a I

±      $22 = 0x65

±     break

±     break许设点,包括行和函数号

±     根据行号设点:

±     (gdb) break file:linenum

±     根据函名;

±     (gdb) break file:func

±     点:

±     (gdb) break line if expr

±     点:

±     (gdb) info break

 

为断行命令

±    commands

±    commands可以定到达断行的命令:

±      (gdb) break foo if x>0

±      (gdb) commands

±      (gdb) printf "x is %dn",x

±      (gdb) continue

±      (gdb) end

变变量的

±    set

±    个变量的,可以用set命令

±    (gdb) set variable varname = value

±    (gdb) print varname = value

码执

±      next

±      next行下一步

±      step

±      step命令入函

±      call

±      call并执行函

±      finish

±      finish中止前函数并打印

±      until

±      until退出前循

±      return

±      停止前函返回value给调用者

shell通信

±    行一个调试会话时,需要用到shell命令,使用的法是:

±    (gdb) shell command

±    比如

±    (gdb) shell pwd

源代文件

±    如果源文件不在前目gdb调试时由于找不到源文件,只能汇编这时可以用-d指定源文件目

±    gdb –d /home/demo_dir  app

跳转执行

±     jump

±     jump提供了行的功能,可以修改程序

±     序,可以程序意跳

±     jump <linespce>

±     指定下一条语句的行点。<linespce>可以是文件的行,可以是file:line格式,可以是+num这种偏移量格式。表式着下一条运从哪始。

±     jump <address>

±     里的<address>是代行的存地址。

线调试

±     如果程序是多线程的可以定义你点是否在所有的线程上,或是在某特定的线程。GDB很容易帮你完成一工作。

±     break <linespec> thread <threadno>

±     break <linespec> thread <threadno> if ...

±     linespec指定了置在的源程序的行threadno指定了线程的ID,注意,这个IDGDB分配的,可以通info threads”命令来查看正在行程序中的线程信息。如果不指定thread <threadno>表示在所有线程上面。

Linux Programming
 gdb in English

Topics

±    The following topics will be covered

®      When do you use gdb

®      Use of gdb

®      Running gdb
®      Setting gdb
®      Examine the data
®      Examine the stack

GDB

±     Use GDB when your program doesnt behave the way you expected - catching the bugs

±     Use GDB when your make files stops on specified condition

±     When you want to examine your program logic to see how it works

Invoking

 

±            Preparing An Executable For Debugging

              $  gcc -o filename filename.c  -g {1,2,3}

                            or

              $    gcc -ggdb -o filename filename.c

 

±            Invoking gdb

              $ gdb filename

 

±            Run program to be debugged

              (gdb) r[un]

 

±            Note: Pressing enter with no command executes the previous command

 

 

Run

Step

Next

Continue

Finish

 

Break

Break

Conditional Breakpoints

±    break [position] if expression

 

(gdb) s

27 for ( i = 1; i <= limit ; ++i )

(gdb) break 28 if i == limit - 1

Breakpoint 1 at 0x4010e7: file gdb_test.c, line 28.

 

±    Once bp reached, expression is evaluated and program stops if true

Watch

Watchpoints

±     watch expression

®      The debugger stops the program when the value of expression changes.

±     rwatch expression

®      The debugger stops the program whenever the program reads the value of any object involved in the evaluation of expression.

±     awatch expression

®      The debugger stops the program whenever the program reads or modifies the value of any object involved in the evaluation of expression.

 

Info

Clear

Delete

Breakpoints

Deleting, Disabling, and Ignoring BP

±        delete [ bp_number | range]

±        d [ bp_number | range]

®         Deletes the specified breakpoint or range of breakpoints. A delete command with no argument deletes all the breakpoints that have been defined. GDB prompts you for confirmation before carrying out such a sweeping command:

®         (gdb) d Delete all breakpoints? (y or n)

±        disable [ bp_number | range]

 

®         Temporarily deactivates a breakpoint or a range of breakpoints. If you don't specify any argument, this command affects all breakpoints. It is often more practical to disable breakpoints temporarily than to delete them. GDB retains the information about the positions and conditions of disabled breakpoints so that you can easily reactivate them.

±        enable [ bp_number | range]

®         Restores disabled breakpoints. If you don't specify any argument, this command affects all disabled breakpoints.

±        ignore bp_number iterations

®         Instructs GDB to pass over a breakpoint without stopping a certain number of times. The ignore command takes two arguments: the number of a breakpoint, and the number of times you want it to be passed over.

 

Print

Display

List

Displaying Source Code

±       list filename: line_number

®         Displays source code centered around the line with the specified line number.

±       list line_number

®         If you do not specify a source filename, then the lines displayed are those in the current source file.

±       list from,[ to]

®         Displays the specified range of the source code. The from and to arguments can be either line numbers or function names. If you do not specify a to argument, list displays the default number of lines beginning at from.

±       list function_name

®         Displays source code centered around the line in which the specified function begins.

±       list, l

®         The list command with no arguments displays more lines of source code following those presented by the last list command. If another command executed since the last list command also displayed a line of source code, then the new list command displays lines centered around the line displayed by that command.

 

 

Backtrace

Analyzing the Stack

±      bt

®       Shows the call trace

±      info frame

®       Displays information about the current stack frame, including its return address and saved register values.

±      info locals

®       Lists the local variables of the function corresponding to the stack frame, with their current values.

±      info args

®       List the argument values of the corresponding function call.

±      info breakpoints or watchpoints

®       List all breakpoints or watchpoints

 

 

Displaying Data

±     p [/format] [expression]

±     Output Formats

®      d: Decimal notation. This is the default format for integer expressions.

®      u: Decimal notation. The value is interpreted as an unsigned integer type.

®      x: Hexadecimal notation.

®      o: Octal notation.

®      t: Binary notation. Do not confuse this with the x command's option b for "byte," described in the next subsection.

®      c: Character, displayed together with the character code in decimal notation.

 

 

 THANKS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值