Tabla de contenidos
Algunos consejos para quién quiera aprender a programar en el sistema Debian para trazar el código fuente. Aquí están los paquetes más importantes y los paquetes de documentación más importantes para la programación.
Tabla 12.1. Lista de paquetes que ayudan a la programación
paquete | popularidad | tamaño | documentación |
---|---|---|---|
autoconf
|
V:29, I:226 | 1868 |
"info autoconf " proporcionado con
autoconf-doc
|
automake
|
V:27, I:220 | 1707 |
"info automake " proporcionado con
automake1.10-doc
|
bash
|
V:853, I:999 | 5799 |
"info bash " proporcionado con bash-doc
|
bison
|
V:10, I:113 | 2061 |
"info bison " proporcionado con
bison-doc
|
cpp
|
V:394, I:806 | 41 |
"info cpp " proporcionado con cpp-doc
|
ddd
|
V:1, I:13 | 3965 |
"info ddd " proporcionado por ddd-doc
|
exuberant-ctags
|
V:7, I:38 | 333 | exuberant-ctags(1) |
flex
|
V:10, I:101 | 1174 |
"info flex " proporcionado por flex-doc
|
gawk
|
V:355, I:478 | 2199 |
"info gawk " proporcionado por gawk-doc
|
gcc
|
V:148, I:606 | 43 |
"info gcc " proporcionado por gcc-doc
|
gdb
|
V:21, I:140 | 7983 |
"info gdb " proporcionado por gdb-doc
|
gettext
|
V:53, I:367 | 7076 |
"info gettext " proporcionado por
gettext-doc
|
gfortran
|
V:20, I:63 | 16 |
"info gfortran " proporcionado por
gfortran-doc (Fortran 95)
|
fpc
|
I:4 | 113 | fpc(1)
y html por fp-docs (Pascal)
|
glade
|
V:1, I:12 | 2209 | proporciona ayuda por medio del menú (Constructor UI) |
libc6
|
V:933, I:999 | 10679 |
"info libc " proporcionado por
glibc-doc y glibc-doc-reference
|
make
|
V:154, I:622 | 1211 |
"info make " proporcionado por make-doc
|
xutils-dev
|
V:2, I:18 | 1466 | imake(1), xmkmf(1), etc. |
mawk
|
V:371, I:997 | 183 | mawk(1) |
perl
|
V:610, I:996 | 651 | perl(1)
y páginas html proporcionadas por perl-doc y
perl-doc-html
|
python
|
V:683, I:988 | 648 | python(1)
y páginas html proporcionado por python-doc |
tcl8.4
|
V:3, I:50 | NOT_FOUND | tcl(3)
y páginas de manual detalladas proporcionadas por
tcl8.4-doc |
tk8.4
|
V:1, I:31 | NOT_FOUND | tk(3)
y páginas de manual detalladas proporcionados por
tk8.4-doc |
ruby
|
V:103, I:321 | 38 | ruby(1)
y la referencia interactiva proporcionada por ri |
vim
|
V:118, I:393 | 2374 |
ayuda(F1) del menú proporacionado por vim-doc
|
susv2
|
I:0 | 15 | cumple "La Especificación Única de UNIX v2" |
susv3
|
I:0 | 15 | cumple "La Especificación Única de UNIX v3" |
Las referencia en línea está disponible escribiendo by typing "man
nombre
" tras instalar los paquetes manpages
y
manpages-dev
. La referencia en línea para las
herramientas GNU están disponibles escribiendo "info
nombre_de_programa
" después de instalar los paquetes
correspondientes de documentación. Pude necesitar incluir los repositorios
contrib
y non-free
además del
repositorio main
ya que una parte de la documentación
GFDL no se cosidera que cumple con DFSG.
![]() |
Aviso |
---|---|
No use" |
![]() |
Atención |
---|---|
Usted puede instalar programas de software directametne compilado de la
fuente en " |
![]() |
Sugerencia |
---|---|
Los ejemplos de código para crear "La canción de 99 botellas de Cerveza" le aportará buenas ideas para pácticamente cualquier lenguaje de programación. |
Un archivo de órdenes es un archivo de texto co el bit de ejecución activado y contiene órdenes con el formato siguiente.
#!/bin/sh ... líneas de órdenes
La primera línea determina el intérprete del shell que se encarga de leer y ejecutar el contenido del archivo.
La lectura de archivos de órdenes es la mejor manera de entender como funciona un sistema tipo Unix. Aquí, doy algunos apuntes para la programación de archivos de órdenes. Consulte "Los errores de los archivos de órdenes" (http://www.greenend.org.uk/rjk/2001/04/shell.html) para aprender los errores más comunes.
No como el modo interactivo de la consola (see Sección 1.5, “Órdenes simples del intérpete de órdenes” and Sección 1.6, “Procesamiento de texto al estilo Unix”) los archivos de órdenes se usan generalmente parámetros, condiciones e iteraciones.
Muchos de los archivos de órdenes pueden ser interpretados por un intérprete
POSIX (consulte Tabla 1.13, “Lista de intérpretes de órdenes”). El intérprete de órdenes del sistema
por defecto es "/bin/sh
" el cual es un enlace simbólico
que referencia al programa actual.
bash(1)
para lenny
o más antiguo
dash(1)
para squeeze
o más nuevo
Evite escribir archivos de órdenes con particularidades de bash o zs para hacerlo portable entre intérpretes de órdenes POSIX. Puede comprobaro utilizando checkbashisms(1).
Tabla 12.2. Enumeración de particularidades de bash
Bien: POSIX | Mal: bashism |
---|---|
if [ "$foo" = "$bar" ] ; then …
|
if [ "$foo" == "$bar" ] ; then …
|
diff -u archivo.c.orig archivo.c
|
diff -u archivo.c{.orig,}
|
mkdir /foobar /foobaz
|
mkdir /foo{bar,baz}
|
funcname() { … }
|
function funcname() { … }
|
octal format: "\377 "
|
formato hexadecimal: "\xff "
|
La órden "echo
" debe utilizarse con cuidado ya que su
implementación cambia entre la órden interna y la externa.
Evite utilizar cualquier opción excepto -n
".
Evite utilizar secuencias de escape en una cadena ya que su tratamiento varia.
![]() |
Nota |
---|---|
Ya que la opción " |
![]() |
Sugerencia |
---|---|
Utilice la órden " |
Frecuentemente son utilizados por el intérprete de órdenes parámetros especiales
Tabla 12.3. Enumeración de los parámetros de intérprete de órdenes
parámetro del intérprete de órdenes | valor |
---|---|
$0
|
nombre del archivo de órdenes |
$1
|
primer argumento del archivo de órdenes |
$9
|
noveno argumento del archivo de órdenes |
$#
|
parámetro posicionado en el número |
"$*"
|
"$1 $2 $3 $4 … "
|
"$@"
|
"$1" "$2" "$3" "$4" …
|
$?
|
estado de finalización de la órden más reciente |
$$
|
PID de este archivo de órdenes |
$!
|
PID del trabajo en segundo plano que se ha iniciado más recientemente |
Lasexpansiones de parámetros fundamentales que debe recordar son las que se muestran.
Tabla 12.4. Enumeración de expansiones de parámetros del intérprete de órdenes
forma de expresión del parámetro |
valor si var esta activado
|
valor si var no está asignado
|
---|---|---|
${var:-string}
|
"$var "
|
"string "
|
${var:+string}
|
"string "
|
"null "
|
${var:=string}
|
"$var "
|
"string " (y ejecuta "var=string ")
|
${var:?string}
|
"$var "
|
echo "string " a stderr
(y finalizar con error)
|
Aquí, el símbolo ":
" en todos estos operadores es ahora
opcional.
con ":
" el operador =
comprueba que existe y no es null
sin ":
" el operador =
comprueba unicamente si existe
Tabla 12.5. Enumeración de las sustituciones clave de parámetros del intérprete de órdenes
formulario de sustitución del parámetro | resultado |
---|---|
${var%suffix}
|
elimina patrón del sufijo más pequeño |
${var%%suffix}
|
elimina el patrón del sufijo más largo |
${var#prefix}
|
elimina el patrón del prefijo más pequeño |
${var##prefix}
|
elimina el patrón del prefijo más largo |
Cada comando devuelve un estado de salida que puede usarse para expresioneos condicionales.
Éxito: 0 ("Verdadero")
Error: no 0 ("Falso")
![]() |
Nota |
---|---|
"0" in the shell conditional context means "True", while "0" in the C conditional context means "False". |
![]() |
Nota |
---|---|
" |
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.
Tabla 12.6. List of file comparison operators in the conditional expression
ecuación | condition to return logical true |
---|---|
-e <file>
|
<file> exists |
-d <file>
|
<file> exists and is a directory |
-f <file>
|
<file> exists and is a regular file |
-w <file>
|
<file> exists and is writable |
-x <file>
|
<file> exists and is executable |
<file1> -nt <file2>
|
<file1> is newer than <file2> (modification) |
<file1> -ot <file2>
|
<file1> is older than <file2> (modification) |
<file1> -ef <file2>
|
<file1> and <file2> are on the same device and the same inode number |
Tabla 12.7. List of string comparison operators in the conditional expression
ecuación | condition to return logical true |
---|---|
-z <str>
|
la longitud de <str> es cero |
-n <str>
|
la longitud de <str> no es cero |
<str1> = <str2>
|
<str1> and <str2> are equal |
<str1> != <str2>
|
<str1> y <str2> no son iguales |
<str1> < <str2>
|
<str1> sorts before <str2> (locale dependent) |
<str1> > <str2>
|
<str1> sorts after <str2> (locale dependent) |
Los operadores aritméticos de comparación
de enteros en la expresión original son "-eq
",
"-ne
", "-lt
",
"-le
", "-gt
" y
"-ge
".
There are several loop idioms to use in POSIX shell.
"for x in foo1 foo2 … ; do comand0 ; done
" asigna
secuencialmente elementos de la lista "foo1 foo2 …
" a la
variable "x
" y ejecuta "comando
".
"while condición ; do comando ; done
" repite
"comando
" mientras "condición
" sea
verdadero.
"until condición ; do comando ; done
" repite
"comando
" mientras "condición
" no sea
verdadero.
"break
" permite salir del bucle.
"continue
" permite continuar con la próxima iteración del
bucle.
![]() |
Sugerencia |
---|---|
The C-language like numeric iteration can be
realized by using
seq(1)
as the " |
![]() |
Sugerencia |
---|---|
Consulta Sección 9.3.9, “Repetición de una órden sobre archivos”. |
The shell processes a script roughly as the following sequence.
The shell reads a line.
The shell groups a part of the line as one
token if it is within "…"
or
'…'
.
The shell splits other part of a line into tokens by the following.
Whitespaces: <space> <tab> <newline>
Metacharacters: < > | ; & ( )
The shell checks the reserved word for
each token to adjust its behavior if not within "…"
or
'…'
.
palabras reservadas: if then
elif else fi for in while unless do done case esac
The shell expands alias if not within
"…"
or '…'
.
The shell expands tilde if not within
"…"
or '…'
.
"~
" → el directorio home del usuario actual
"~<usuario>
" → el directorio home de
<usuario>
The shell expands parameter to its value
if not within '…'
.
parameter:
"$PARAMETER
" or "${PARAMETER}
"
The shell expands command substitution if
not within '…'
.
"$( comando )
" → la salida de
"comando
"
"` comando `
" → la salida de "comando
"
The shell expands pathname glob to
matching file names if not within "…"
or
'…'
.
*
→ cualesquier caracteres
?
→ un caracter
[…]
→ cualquiera de los caracteres en
"…
"
The shell looks up command from the following and execute it.
function definition
builtin command
executable file in
"$PATH
"
The shell goes to the next line and repeats this process again from the top of this sequence.
Las comillas simples no tienen efecto dentro de comillas dobles.
Executing "set -x
" in the shell or invoking the shell
with "-x
" option make the shell to print all of commands
executed. This is quite handy for debugging.
In order to make your shell program as portable as possible across Debian systems, it is a good idea to limit utility programs to ones provided by essential packages.
"aptitude search ~E
" lista paquetes esenciales.
"dpkg -L <paquete> | grep '/man/man.*/'
" lista
páginas 'man' para los comandos que ofrece
<paquete>
.
Tabla 12.8. List of packages containing small utility programs for shell scripts
paquete | popularidad | tamaño | descripción |
---|---|---|---|
coreutils
|
V:881, I:999 | 15103 | GNU core utilities |
debianutils
|
V:934, I:999 | 213 | miscellaneous utilities specific to Debian |
bsdmainutils
|
V:866, I:998 | 566 | collection of more utilities from FreeBSD |
bsdutils
|
V:851, I:999 | 238 | basic utilities from 4.4BSD-Lite |
moreutils
|
V:4, I:19 | 201 | additional Unix utilities |
![]() |
Sugerencia |
---|---|
Although |
The user interface of a simple shell program can be improved from dull
interaction by echo
and read
commands
to more interactive one by using one of the so-called dialog program etc.
Tabla 12.9. List of user interface programs
paquete | popularidad | tamaño | descripción |
---|---|---|---|
x11-utils
|
V:305, I:635 | 637 | xmessage(1): display a message or query in a window (X) |
whiptail
|
V:415, I:995 | 68 | displays user-friendly dialog boxes from shell scripts (newt) |
dialog
|
V:29, I:151 | 1111 | displays user-friendly dialog boxes from shell scripts (ncurses) |
zenity
|
V:112, I:425 | 362 | display graphical dialog boxes from shell scripts (gtk2.0) |
ssft
|
V:0, I:0 | 129 | Shell Scripts Frontend Tool (wrapper for zenity, kdialog, and dialog with gettext) |
gettext
|
V:53, I:367 | 7076 |
"/usr/bin/gettext.sh ": translate message
|
Here is a simple script which creates ISO image with RS02 data supplemented by dvdisaster(1).
#!/bin/sh -e # gmkrs02 : Copyright (C) 2007 Osamu Aoki <osamu@debian.org>, 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
You may wish to create launcher on the desktop with command set something
like "/usr/local/bin/gmkrs02 %d
".
Make is a utility to maintain groups of
programs. Upon execution of
make(1),
make
read the rule file, "Makefile
",
and updates a target if it depends on prerequisite files that have been
modified since the target was last modified, or if the target does not
exist. The execution of these updates may occur concurrently.
The rule file syntax is the following.
target: [ prerequisites ... ] [TAB] command1 [TAB] -command2 # ignore errors [TAB] @command3 # suppress echoing
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.
Implicit rules for the target and prerequisites can be written, for example, by the following.
%.o: %.c header.h
Here, the target contains the character "%
" (exactly one
of them). The "%
" can match any nonempty substring in the
actual target filenames. The prerequisites likewise use
"%
" to show how their names relate to the actual target
name.
Tabla 12.10. List of make automatic variables
variable automática | valor |
---|---|
$@
|
target |
$<
|
first prerequisite |
$?
|
all newer prerequisites |
$^
|
all prerequisites |
$*
|
"% " matched stem in the target pattern
|
Tabla 12.11. List of make variable expansions
expansión variable | descripción |
---|---|
foo1 := bar
|
expansión por única vez |
foo2 = bar
|
expansión recursiva |
foo3 += bar
|
anexar |
Run "make -p -f/dev/null
" to see automatic internal
rules.
You can set up proper environment to compile programs written in the C programming language by the following.
# apt-get install glibc-doc manpages-dev libc6-dev gcc build-essential
The libc6-dev
package, i.e., GNU C Library, provides
C standard library which is
collection of header files and library routines used by the C programming
language.
See references for C as the following.
"info libc
" (C library function reference)
gcc(1)
y "info gcc
"
each_C_library_function_name(3)
Kernighan & Ritchie, "The C Programming Language", 2nd edition (Prentice Hall)
Se puede crear un ejecutable "ejecutable_de_ejemplo
"
utilizando la biblioteca "libm
" mediante este sencillo
ejemplo.
$ cat > ejemplo.c << EOF #include <stdio.h> #include <math.h> #include <string.h> int main(int argc, char **argv, char **envp){ double x; char y[11]; x=sqrt(argc+7.5); strncpy(y, argv[0], 10); /* evita el desbordamiento */ y[10] = '\0'; /* asegura que la cadena finaliza con '\0' */ printf("%5i, %5.3f, %10s, %10s\n", argc, x, y, argv[1]); return 0; } EOF $ gcc -Wall -g -o ejecutable_de_ejemplo ejemplo..c -lm $ ./ejecutable_de_ejemplo 1, 2.915, ./run_exam, (null) $ ./run_example 1234567890qwerty 2, 3.082, ./run_exam, 1234567890qwerty
Aquí, se necesita "-lm
" para enlazar la biblioteca
"/usr/lib/libm.so
" del paquete libc6
para utilizar la función
sqrt(3).
La biblioteca actual está ubicada en "/lib/
" con el
nombre de archivo "libm.so.6
", el cual es un enlace
simbólico a "libm-2.7.so
".
Mire el último elemento de la salida. Tiene incluso más de 10 caracteres a
pesar de tener "%10s
".
La utilización de operaciones de punteros sin comprobar los límites, como ocurre con sprintf(3) y strcpy(3), no se utilizan para evitar el desbordamiento del buffer que puede provocar problemas desconocidos. En su lugar se utilizan snprintf(3) y strncpy(3).
La depuración es una de las actividades más importantes de la programación. Conocer como depurar un programa le convierte en un usuario de Debian mejor que puede aportar informes de error relevantes.
El principal depurador en Debian es gdb(1) el cual permite inspeccionar un programa mientras se ejecuta.
Instalemo gdb
y otros programas relevantes com se
muestra.
# apt-get install gdb gdb-doc build-essential devscripts
Puede encontrar un buen tutorial de gdb
en "info
gdb
" y mucha más información a
través de Internet. Aquí hay un ejemplo sencillo de la utilización
de
gdb(1)
en un "programa
" que ha sido compilado para producir
información de depuración con la opción "-g
".
$ gdb programa (gdb) b 1 # pone un punto de ruptura en la línea 1 (gdb) run args # ejecuta el programa con args (gdb) next # siguiente línea ... (gdb) step # paso hacia adelante ... (gdb) p parm # imprime el valor de parm ... (gdb) p parm=12 # le asigna el valor de 12 ... (gdb) quit
![]() |
Sugerencia |
---|---|
Existen abreviaturas para la mayor parte de las órdenes de gdb(1). La expansión del tabulador funciona de la misma manera que en el intérprete de órdenes. |
Por defecto, en un paquete normal, los binarios del sistema Debian deben
estar limpios por lo que la mayor parte de los símbolos del sistema son
eliminados. Para depurar un paquete Debian con
gdb(1),
se necesita la instalación de los paquetes *-dbg
(p. ej. libc6-dbg
en el caso de la
libc6
).
If a package to be debugged does not provide its *-dbg
package, you need to install it after rebuilding it by the following.
$ mkdir /path/new ; cd /path/new $ sudo apt-get update $ sudo apt-get dist-upgrade $ sudo apt-get install fakeroot devscripts build-essential $ sudo apt-get build-dep source_package_name $ apt-get source package_name $ cd package_name*
Fix bugs if needed.
Bump package version to one which does not collide with official Debian
versions, e.g. one appended with "+debug1
" when
recompiling existing package version, or one appended with
"~pre1
" when compiling unreleased package version by the
following.
$ dch -i
Compile and install packages with debug symbols by the following.
$ export DEB_BUILD_OPTIONS=nostrip,noopt $ debuild $ cd .. $ sudo debi package_name*.changes
You need to check build scripts of the package and ensure to use
"CFLAGS=-g -Wall
" for compiling binaries.
When you encounter program crash, reporting bug report with cut-and-pasted backtrace information is a good idea.
The backtrace can be obtained by the following steps.
Run the program under gdb(1).
Reproduce crash.
It causes you to be dropped back to the gdb
prompt.
Type "bt
" at the gdb
prompt.
In case of program freeze, you can crash the program by pressing
Ctrl-C
in the terminal running gdb
to
obtain gdb
prompt.
![]() |
Sugerencia |
---|---|
Often, you see a backtrace where one or more of the top lines are in
" |
$ MALLOC_CHECK_=2 gdb hello
Tabla 12.12. List of advanced gdb commands
orden | description for command objectives |
---|---|
(gdb) thread apply all bt
|
get a backtrace for all threads for multi-threaded program |
(gdb) bt full
|
get parameters came on the stack of function calls |
(gdb) thread apply all bt full
|
get a backtrace and parameters as the combination of the preceding options |
(gdb) thread apply all bt full 10
|
get a backtrace and parameters for top 10 calls to cut off irrelevant output |
(gdb) set logging on
|
write log of gdb output to a file (the default is
"gdb.txt ")
|
If a GNOME program preview1
has received an X error, you
should see a message as follows.
The program 'preview1' received an X Window System error.
If this is the case, you can try running the program with
"--sync
", and break on the
"gdk_x_error
" function in order to obtain a backtrace.
Use ldd(1) to find out a program's dependency on libraries by the followings.
$ ldd /bin/ls librt.so.1 => /lib/librt.so.1 (0x4001e000) libc.so.6 => /lib/libc.so.6 (0x40030000) libpthread.so.0 => /lib/libpthread.so.0 (0x40153000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
For ls(1) to work in a `chroot`ed environment, the above libraries must be available in your `chroot`ed environment.
There are several memory leak detection tools available in Debian.
Tabla 12.13. List of memory leak detection tools
paquete | popularidad | tamaño | descripción |
---|---|---|---|
libc6-dev
|
V:269, I:615 | 15628 | mtrace(1): malloc debugging functionality in glibc |
valgrind
|
V:8, I:56 | 70463 | memory debugger and profiler |
kmtrace
|
V:1, I:18 | 351 | KDE memory leak tracer using glibc's mtrace(1) |
alleyoop
|
V:0, I:1 | 655 | GNOME front-end to the Valgrind memory checker |
electric-fence
|
V:0, I:6 | 70 | malloc(3) debugger |
leaktracer
|
V:0, I:2 | 56 | memory-leak tracer for C++ programs |
libdmalloc5
|
V:0, I:3 | 360 | debug memory allocation library |
There are lint like tools for static code analysis.
Tabla 12.14. List of tools for static code analysis
paquete | popularidad | tamaño | descripción |
---|---|---|---|
splint
|
V:0, I:5 | 1889 | tool for statically checking C programs for bugs |
flawfinder
|
V:0, I:1 | 175 | tool to examine C/C++ source code and looks for security weaknesses |
perl
|
V:610, I:996 | 651 | interpreter with internal static code checker: B::Lint(3perl) |
pylint
|
V:6, I:15 | 945 | Python code static checker |
weblint-perl
|
V:0, I:2 | 34 | syntax and minimal style checker for HTML |
linklint
|
V:0, I:1 | 343 | fast link checker and web site maintenance tool |
libxml2-utils
|
V:24, I:318 | 177 | utilities with xmllint(1) to validate XML files |
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.
Tabla 12.15. List of Yacc-compatible LALR parser generators
paquete | popularidad | tamaño | descripción |
---|---|---|---|
bison
|
V:10, I:113 | 2061 | GNU LALR parser generator |
byacc
|
V:0, I:7 | 160 | Berkeley LALR parser generator |
btyacc
|
V:0, I:0 | 207 |
backtracking parser generator based on byacc
|
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.
![]() |
Aviso |
---|---|
Do not overwrite system files with your compiled programs when installing them. |
Debian does not touch files in "/usr/local/
" or
"/opt
". So if you compile a program from source, install
it into "/usr/local/
" so it does not interfere with
Debian.
$ cd src $ ./configure --prefix=/usr/local $ make $ make install # this puts the files in the system
If you have the original source and if it uses autoconf(1)/automake(1) and if you can remember how you configured it, execute as follows to uninstall the program.
$ ./configure "all-of-the-options-you-gave-it" # make uninstall
Alternatively, if you are absolutely sure that the install process puts
files only under "/usr/local/
" and there is nothing
important there, you can erase all its contents by the following.
# find /usr/local -type f -print0 | xargs -0 rm -f
If you are not sure where files are installed, you should consider using
checkinstall(8)
from the checkinstall
package, which provides a clean
path for the uninstall. It now supports to create a Debian package with
"-D
" option.
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
"
"%nn
" in URL is replaced with a character with
hexadecimal nn
value.
The environment variable is set as: "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
".
stdout
of CGI program is sent to the web browser and is
presented as an interactive dynamic web page.
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.
For more, see the Common Gateway Interface, The Apache Software Foundation, and 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.
There are programs to convert source codes.
Tabla 12.16. List of source code translation tools
paquete | popularidad | tamaño | palabra clave | descripción |
---|---|---|---|---|
perl
|
V:610, I:996 | 651 | AWK→PERL | convert source codes from AWK to PERL: a2p(1) |
f2c
|
V:0, I:7 | 433 | FORTRAN→C | convert source codes from FORTRAN 77 to C/C++: f2c(1) |
intel2gas
|
V:0, I:0 | 174 | intel→gas | converter from NASM (Intel format) to the GNU Assembler (GAS) |
If you want to make a Debian package, read followings.
Capítulo 2, Gestión de paquetes Debian to understand the basic package system
Sección 2.7.13, “Portar un paquete a un sistema estable” to understand basic porting process
Sección 9.10.4, “Sistemas chroot” to understand basic chroot techniques
debuild(1), pbuilder(1) and pdebuild(1)
Sección 12.4.2, “Depurando un paquete Debian” for recompiling for debugging
Debian New Maintainers'
Guide as tutorial (the maint-guide
package)
Debian Developer's
Reference (the developers-reference
package)
Debian Policy Manual (the
debian-policy
package)
Guide for Debian
Maintainers (the debmake-doc
package)
There are packages such as debmake
,
dh-make
, dh-make-perl
, etc., which
help packaging.