出售域名

第 12 章 编程

目录

12.1. Shell 脚本
12.1.1. POSIX shell 兼容性
12.1.2. Shell 参数
12.1.3. Shell conditionals
12.1.4. shell 循环
12.1.5. shell 命令行的处理顺序
12.1.6. 用于 shell 脚本的应用程序
12.1.7. shell 脚本对话框
12.1.8. zenity 的 shell 脚本案例
12.2. make
12.3. C
12.3.1. 简单的 C 程序(gcc)
12.4. 调试
12.4.1. 基本的 gdb 使用命令
12.4.2. 调试 Debian 软件包
12.4.3. Obtaining backtrace
12.4.4. 高级 gdb 命令
12.4.5. Debugging X Errors
12.4.6. 检查库依赖性
12.4.7. 内存泄漏检测工具
12.4.8. 静态代码分析工具
12.4.9. 反汇编二进制程序
12.5. Flex — 一个更好的Lex
12.6. Bison — a better Yacc
12.7. Autoconf
12.7.1. 编译并安装程序
12.7.2. 卸载程序
12.8. Perl short script madness
12.9. Web
12.10. 源代码转换
12.11. 制作 Debian 包

这里我给出一些 Debian 系统中的信息,帮助学习编程的人找出打包的源代码。下面是值得关注的软件包和与之对应的文档。

表 12.1. 帮助编程的软件包清单

软件包 流行度 大小
autoconf V:29, I:222 1868 autoconf-doc 包提供的“info autoconf
automake V:27, I:214 1707 automake1.10-doc 包提供的“info automake
bash V:857, I:999 5798 bash-doc 包提供的“info bash
bison V:12, I:114 2051 bison-doc 包提供的“info bison
cpp V:403, I:813 41 cpp-doc 包提供的“info cpp
ddd V:1, I:13 3692 ddd-doc 包提供的“info ddd
exuberant-ctags V:7, I:37 333 exuberant-ctags(1)
flex V:11, I:102 1174 flex-doc 包提供的“info flex
gawk V:356, I:470 2029 gawk-doc 包提供的“info gawk
gcc V:157, I:611 41 gcc-doc 包提供的“info gcc
gdb V:22, I:142 7865 gdb-doc 包提供的“info gdb
gettext V:58, I:371 7035 gettext-doc 包提供的“info gettext
gfortran V:22, I:62 16 gfortran-doc 包提供的“info gfortran”(Fortran 95)
fpc I:4 113 fpc(1) 和由 fp-docs 包提供的 html 文档(Pascal)
glade V:1, I:12 2209 通过 UI Builder 菜单提供的文档
libc6 V:928, I:998 10670 通过 glibc-docglibc-doc-reference 提供的“info libc
make V:161, I:626 1195 通过 make-doc 包提供的“info make
xutils-dev V:2, I:19 1465 imake(1)xmkmf(1) 等。
mawk V:397, I:997 198 mawk(1)
perl V:609, I:995 651 perl(1) 以及通过 perl-docperl-doc-html 提供的 html 文档
python V:676, I:988 647 python(1) 以及通过 python-doc 包提供的 html 文档
tcl8.4 V:4, I:61 184 tcl(3) 以及通过 tcl8.4-doc 包提供的更详细的手册页文档
tk8.4 V:2, I:39 185 tk(3) 以及通过 tk8.4-doc 包提供的更详细的手册页文档
ruby V:91, I:317 37 ruby(1) 以及通过 ri 包提供的交互式参考手册
vim V:112, I:391 2366 通过 vim-doc 包提供的帮助(F1)菜单
susv2 I:0 15 通过“单一UNIX规范(版本2)”获取(英语文档)
susv3 I:0 15 通过“单一UNIX规范(版本3)”获取(英语文档)

安装 manpagesmanpages-dev 包之后,可以通过运行“man 名称”查看手册页中的参考信息。安装了 GNU 工具的相关文档包之后,可以通过运行“info 程序名称”查看参考文档。某些 GFDL 协议的文档与 DFSG 并不兼容,所以你可能需要在 main 仓库中包含 contribnon-free 才能下载并安装它们。

[警告] 警告

不要用“test”作为可执行的测试文件的名字,因为 shell 中内建有“test”命令。

[小心] 小心

你可以把从源代码编译得到的程序直接放到“/usr/local”或“/opt”目录,这样可以避免与系统程序撞车。

[提示] 提示

“歌曲:99瓶啤酒”的代码示例可以给你提供实践各种语言的好范本。

Shell 脚本 是指包含有下面格式的可执行的文本文件。

#!/bin/sh
…… 命令

第一行指明了读取并执行这个文件的 shell 解释器。

读懂 shell 脚本的最好 办法是先理解类 UNIX 系统是如何工作的。这里有一些 shell 编程的提示。看看“Shell 错误”(http://www.greenend.org.uk/rjk/2001/04/shell.html),可以从错误中学习。

不像 shell 交互模式(参见第 1.5 节 “简单 shell 命令”第 1.6 节 “类 Unix 的文本处理”),shell 脚本会频繁使用参数、条件和循环等。

Each command returns an exit status which can be used for conditional expressions.

  • Success: 0 ("True")

  • Error: non 0 ("False")

[注意] 注意

"0" in the shell conditional context means "True", while "0" in the C conditional context means "False".

[注意] 注意

"[" is the equivalent of the test command, which evaluates its arguments up to "]" as a conditional expression.

Basic conditional idioms to remember are the following.

  • "<command> && <if_success_run_this_command_too> || true"

  • "<command> || <if_not_success_run_this_command_too> || true"

  • A multi-line script snippet as the following

if [ <conditional_expression> ]; then
 <if_success_run_this_command>
else
 <if_not_success_run_this_command>
fi

Here trailing "|| true" was needed to ensure this shell script does not exit at this line accidentally when shell is invoked with "-e" flag.



算术整数的比较在条件表达式中为 "-eq","-ne","-lt","-le","-gt" 和 "-ge"。

下面是一个简单的脚本,它通过 dvdisaster(1) 创建了带有 RS02 补充数据的 ISO 映像。

#!/bin/sh -e
# gmkrs02 : Copyright (C) 2007 Osamu Aoki <[email protected]>, Public Domain
#set -x
error_exit()
{
  echo "$1" >&2
  exit 1
}
# Initialize variables
DATA_ISO="$HOME/Desktop/iso-$$.img"
LABEL=$(date +%Y%m%d-%H%M%S-%Z)
if [ $# != 0 ] && [ -d "$1" ]; then
  DATA_SRC="$1"
else
  # Select directory for creating ISO image from folder on desktop
  DATA_SRC=$(zenity --file-selection --directory  \
    --title="Select the directory tree root to create ISO image") \
    || error_exit "Exit on directory selection"
fi
# Check size of archive
xterm -T "Check size $DATA_SRC" -e du -s $DATA_SRC/*
SIZE=$(($(du -s $DATA_SRC | awk '{print $1}')/1024))
if [ $SIZE -le 520 ] ; then
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is good for CD backup:\\n $SIZE MB"
elif [ $SIZE -le 3500 ]; then
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is good for DVD backup :\\n $SIZE MB"
else
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is too big to backup : $SIZE MB"
  error_exit "The data size is too big to backup :\\n $SIZE MB"
fi
# only xterm is sure to have working -e option
# Create raw ISO image
rm -f "$DATA_ISO" || true
xterm -T "genisoimage $DATA_ISO" \
  -e genisoimage -r -J -V "$LABEL" -o "$DATA_ISO" "$DATA_SRC"
# Create RS02 supplemental redundancy
xterm -T "dvdisaster $DATA_ISO" -e  dvdisaster -i "$DATA_ISO" -mRS02 -c
zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
  --text="ISO/RS02 data ($SIZE MB) \\n created at: $DATA_ISO"
# EOF

你可能想要在桌面创建一个启动器,其中的命令设置为类似 “/usr/local/bin/gmkrs02 %d” 的形式。

Make 是一个维护程序组的工具。一旦执行 make(1)make 会读取规则文件 Makefile,自从上次目标文件被修改后,如果目标文件依赖的相关文件发生了改变,那么就会更新目标文件,或者目标文件不存在,那么这些文件更新可能会同时发生。

规则文件的语法如下所示。

目标:[相关文件 ...]
[TAB] 命令1
[TAB] -命令2 # 忽略错误
[TAB] @命令3 # 禁止回显

Here "[TAB]" is a TAB code. Each line is interpreted by the shell after make variable substitution. Use "\" at the end of a line to continue the script. Use "$$" to enter "$" for environment values for a shell script.

目标跟相关文件也可以通过隐式规则给出,例如,如下所示。

%.o: %.c header.h

在这里,目标包含了 "%" 字符 (只是它们中确切的某一个)。"%" 字符能够匹配实际的目标文件中任意一个非空的子串。相关文件同样使用 "%" 来表明它们是怎样与目标文件建立联系的。



运行 "make -p -f/dev/null" 命令来查看内部自动化的规则。

你可以通过下列方法设置适当的环境来编译使用 C 编程语言编写的程序。

# apt-get install glibc-doc manpages-dev libc6-dev gcc build-essential

libc6-dev 软件包,即 GNU C 库,提供了 C 标准库,它包含了 C 编程语言所使用的头文件和库例程。

参考信息如下。

  • info libc”(C 库函数参考)

  • gcc(1) 和 “info gcc

  • each_C_library_function_name(3)

  • Kernighan & Ritchie,“C 程序设计语言”,第二版(Prentice Hall)

调试是程序中很重要的一部分。知道怎样去调试程序使得作为 Debian 使用者的你, 能够做出有意义的错误报告。

Debian 上原始的调试器gdb(1), 它能让你在程序执行的时候检查程序。

让我们通过如下所示的命令来安装 gdb 及其相关程序。

# apt-get install gdb gdb-doc build-essential devscripts

gdb 的好的教程由 "info gdb" 提供或者可以在网上的其他地方找到。如下是用 gdb(1) 在"程序"带有 "-g" 选项编译的时候来产生调试信息。

$ gdb program
(gdb) b 1                # 在第一行设置断点
(gdb) run args           # 带参数运行程序
(gdb) next               # 执行下一步
...
(gdb) step               # 单步进入
...
(gdb) p parm             # 打印 parm 的值
...
(gdb) p parm=12          # 把值设为 12
...
(gdb) quit
[提示] 提示

许多 gdb(1) 命令都能被缩写。Tab 扩展跟在 shell 一样都能工作。

Flex is a Lex-compatible fast lexical analyzer generator.

Tutorial for flex(1) can be found in "info flex".

You need to provide your own "main()" and "yywrap()". Otherwise, your flex program should look like this to compile without a library. This is because that "yywrap" is a macro and "%option main" turns on "%option noyywrap" implicitly.

%option main
%%
.|\n    ECHO ;
%%

Alternatively, you may compile with the "-lfl" linker option at the end of your cc(1) command line (like AT&T-Lex with "-ll"). No "%option" is needed in this case.

Several packages provide a Yacc-compatible lookahead LR parser or LALR parser generator in Debian.


Tutorial for bison(1) can be found in "info bison".

You need to provide your own "main()" and "yyerror()". "main()" calls "yyparse()" which calls "yylex()", usually created with Flex.

%%
%%

Autoconf is a tool for producing shell scripts that automatically configure software source code packages to adapt to many kinds of Unix-like systems using the entire GNU build system.

autoconf(1) produces the configuration script "configure". "configure" automatically creates a customized "Makefile" using the "Makefile.in" template.

Although any AWK scripts can be automatically rewritten in Perl using a2p(1), one-liner AWK scripts are best converted to one-liner Perl scripts manually.

Let's think following AWK script snippet.

awk '($2=="1957") { print $3 }' |

This is equivalent to any one of the following lines.

perl -ne '@f=split; if ($f[1] eq "1957") { print "$f[2]\n"}' |
perl -ne 'if ((@f=split)[1] eq "1957") { print "$f[2]\n"}' |
perl -ne '@f=split; print $f[2] if ( $f[1]==1957 )' |
perl -lane 'print $F[2] if $F[1] eq "1957"' |
perl -lane 'print$F[2]if$F[1]eq+1957' |

The last one is a riddle. It took advantage of following Perl features.

  • The whitespace is optional.

  • The automatic conversion exists from number to the string.

See perlrun(1) for the command-line options. For more crazy Perl scripts, Perl Golf may be interesting.

Basic interactive dynamic web pages can be made as follows.

  • Queries are presented to the browser user using HTML forms.

  • Filling and clicking on the form entries sends one of the following URL string with encoded parameters from the browser to the web server.

    • "http://www.foo.dom/cgi-bin/program.pl?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"

    • "http://www.foo.dom/cgi-bin/program.py?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"

    • "http://www.foo.dom/program.php?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"

  • 在 URL 里面 "%nn" 是使用一个 16 进制字符的 nn 值代替。

  • 环境变量设置为: "QUERY_STRING="VAR1=VAL1 VAR2=VAL2 VAR3=VAL3"".

  • CGI program (any one of "program.*") on the web server executes itself with the environment variable "$QUERY_STRING".

  • CGI 程序的 stdout发送到浏览器,作为交互式的动态 web 页面展示。

For security reasons it is better not to hand craft new hacks for parsing CGI parameters. There are established modules for them in Perl and Python. PHP comes with these functionalities. When client data storage is needed, HTTP cookies are used. When client side data processing is needed, Javascript is frequently used.

更多信息,参见 通用网关接口, Apache 软件基金会, 和 JavaScript.

Searching "CGI tutorial" on Google by typing encoded URL http://www.google.com/search?hl=en&ie=UTF-8&q=CGI+tutorial directly to the browser address is a good way to see the CGI script in action on the Google server.

源代码转换程序。


如果你想制作一个 Debian 包,阅读下面内容。

debmake, dh-make, dh-make-perl 等软件包,对软件包打包过程,也有帮助。


host by aosp.me  CDN