Sistema Operativo Linux 2022
Sistema Operativo Linux 2022
1. Fundamentos de Unix/Linux
1.1 Sistema Operativo Unix/Linux
Cuando se trabaja con un sistema informático moderno (por ejemplo al escribir un texto), no se accede
directamente a los componentes físicos de la máquina (el hardware), sino que el acceso se realiza a través de
los programas instalados. El programa básico de un computador es el sistema operativo, que se encarga de
coordinar las funciones de los dispositivos de entrada, como el teclado o el mouse, y de los de salida, como
monitor e impresora. Además, se encarga de proporcionar recursos del sistema (como por ejemplo memoria
o procesador) a los distintos programas y vigila que un determinado programa no utilice una zona de memoria
ya ocupada.
An Operating System (OS) is a set of programs whose purpose is to provide a way of managing resources
of a computer system and also to provide an interface for interaction with human beings. Computer resources
to be managed by an OS include CPU, RAM, and I/O devices. These I/O devices include secondary storage
devices (HDD, CD, DVD, USB, etc.) and communication devices like wired networking (Ethernet) or wireless
networking (Wifi), etc. From the above discussion, we can say that two key issues for an OS are:
• Resources management. For example, in all modern computer systems, it is possible to run more
than one process simultaneously. So, the OS is responsible for allocating the CPU execution cycles
and the RAM memory required by each process. An introduction to which is the organization of the
Linux OS which allows this OS to achieve a proper way of managing and accessing system resources
is provided in Section 1.2.
• User Interaction. Another essential issue is how the OS allows interaction between the user (human
being) and the computer. This interaction includes operations over the file system (copy, move, and
delete files), execution of programs, network configuration, and so on. The two main system
interfaces for interaction between the user and the computer - CLI and GUI - are further discussed
in Section 1.4.
The kernel is the main component of most computer operating systems. It is a bridge between applications
and the actual data processing done at the hardware level. The kernel’s primary function is to manage the
computer’s resources and allow other programs to run and use these resources. Typically, the resources
consist of:
• Central Processing Unit (CPU). This is the most central part of a computer system, responsible for
running or executing programs on it. The kernel takes responsibility for deciding at any time which
of the many running programs should be allocated to the processor or processors (each of which can
usually run only one program at a time).
• Memory. Memory is used to store both program instructions and data. Typically, both need to be
present in memory in order for a program to execute. Often multiple programs will want access to
memory, frequently demanding more memory than the computer has available. The kernel is
responsible for deciding which memory each process can use, and determining what to do when not
enough is available.
• Input/Output (I/O) Devices. I/O devices present in the computer, such as keyboard, mouse, disk
drives, printers, displays, etc. The kernel allocates requests from applications to perform I/O to an
appropriate device (or subsection of a device, in the case of files on a disk or windows on a display)
and provides convenient methods for using the device (typically abstracted to the point where the
application does not need to know implementation details of the device).
The kernel typically makes these facilities available to application processes through system calls (see Figure
1.3).
A system call defines how a program requests a service from an operating system’s kernel. This may include
hardware related services (for e.g. accessing the Hard Disk), creating and executing new processes, and
communicating with integral kernel services (like scheduling). System calls provide the interface between a
process and the operating system. Most operations interacting with the system require permissions not
available to a user level process, e.g. I/O performed with a device present on the system, or any form of
communication with other processes requires the use of system calls.
connected to the system. Without modules, we would have to build monolithic kernels and add new
functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of
requiring us to rebuild and reboot the kernel every time we want new functionality. Modules or drivers
interact with devices like hard disks, printers, network cards etc. and provide system calls. Modules can be
statically compiled with the kernel or they can be dynamically loaded. The commands related with modules
are lsmod, insmod and modprobe.
Finally, we will discuss the Linux Booting Sequence. To start a Linux system (see Figure 1.4), we need
to follow a startup sequence in which the flow control goes from the BIOS to the boot manager2 and finally to
the Linux-core (kernel).
boot process will be different depending on the architecture processor and the BIOS.
As mentioned, Unix-like systems are multiprocess and to manage the processes the kernel starts a scheduler
and executes the initialization program init. init sets the user environment and allows user interaction and the
log in, then the core keeps itself idle until it is called. In summary, after you boot Linux:
• The kernel starts a scheduler and executes the initialization program init.
• Once init has started it can create other processes. In particular, init sets the user environment and
allows user interaction and the log in, and then the core keeps itself idle until it is called.
• The processes can be parents and children and both at the same time.
Una computadora equipada con Unix puede ejecutar varios programas simultáneamente, por lo tanto no es
necesario esperar a que finalice la ejecución de un comando para introducir el siguiente.
• Capacidad multiusuario.
Varios usuarios pueden trabajar simultáneamente en un computador con Unix. Esto no significa que varios
usuarios compartan un teclado y una pantalla, sino que pueden acceder al mismo a través de una red desde
su propia máquina.
Uno de los objetivos en el diseño de todos los sistemas operativos de la familia UNIX, era posibilitar
que varios usuarios pudieran utilizar simultáneamente el sistema (capacidad de multiusuario). Puesto que los
usuarios desean ejecutar simultáneamente varios programas, deben existir mecanismos que permitan
ejecutarlos simultáneamente (capacidad de multitarea).
Otros sistemas operativos (como, por ejemplo, MAC OS. X) no intervienen en la descarga del proceso;
en ese caso para que pueda ejecutarse otro proceso, el control sobre el procesador lo tiene que dejar
explícitamente el proceso actual. Esto puede provocar que un proceso monopolice el procesador y que otros
procesos no dispongan de él. Esto tiene como consecuencia un bloqueo del sistema.
Una función importante del sistema operativo es proporcionar el acceso coordinado a los recursos
existentes en el sistema (disco duro, cd ROM, interfaces). En el caso de acceso simultáneo a un cd ROM, solo
se debe ceder el acceso a un proceso mientras se deniega a los restantes.
Esta función de coordinación es muy compleja y muy pocos sistemas operativos ofrecen una solución
completa. El error clásico que se puede producir es la situación en la que varios procesos requieren
exclusivamente diferentes recursos.
Una ampliación del procesamiento multitarea es el “multithreading” (multihebra). Con ello, dentro
de un proceso se pueden generar partes independientes unas de otras (“threads”). El “multithreading”
aumenta el grado de paralelismo y con ello un mayor aprovechamiento del procesador (respectivamente de
los procesadores). Pero esto tiene también un precio, ya que esas unidades adicionales tienen que ser también
administradas.
Sin embargo, especialmente en sistemas multiprocesador, se obtienen grandes ventajas con ello.Se debe
diferenciar claramente entre programas y procesos: un programa existe normalmente sólo una vez en un
sistema, pero puede haber más de un proceso que ejecute el mismo programa. Si hay varios usuarios activos
todos pueden, independientemente unos de otros, por ejemplo, utilizar el programa para listar archivos.
Con la ayuda de la memoria virtual, los procesos pueden ejecutarse hasta la siguiente capacidad máxima:
Tamaño de procesos = RAM + espacio de disco configurado. Los sistemas “swap” puros descargan la memoria
de todo el proceso desde la RAM al disco duro. Los sistemas puros de paginación (“paging”) desglosan los
procesos en páginas de memoria y en el caso de faltar ésta, descargan las páginas que menos se utilizan.
Los sistemas actuales de Unix emplean una combinación de ambos mecanismos. Normalmente se utiliza la
paginación y sólo se descargan completamente (“swap out”) los procesos que están durante mucho tiempo
inactivos.
Bajo Unix, esta diferenciación no se mantiene de forma consecuente, por ejemplo, se refiere al
espacio reservado para la descarga de páginas como área “swap”, y todas las actividades de descarga se
llaman “swapping”, incluso en los casos en los que realmente se trata de paginación.
La correspondencia entre las direcciones “virtuales” y las “reales” se realiza mediante la ayuda de
tablas. Una parte de la dirección sirve como índice en la tabla, allí se encuentra la dirección de la página
buscada (en la RAM o en el disco). Esta representación es completamente transparente para los procesos de
usuario que no tienen posibilidad de acceder directamente a la RAM. Si la denominada dirección de memoria
no existe en la RAM entonces automáticamente el sistema operativo carga la información desde el disco en
una página RAM vacía. Sólo después continuará el proceso utilizado.
Cuando la memoria real disponible se aprovecha casi en su totalidad, entonces la carga y descarga de páginas
puede disminuir sustancialmente el rendimiento del sistema. En situaciones extremas se puede llegar al caso
en el que apenas se puede trabajar con el sistema – esa situación se denomina “thrashing”, en ella
prácticamente sólo se cargan y descargan páginas.
In the past, UNIX mainframe systems had several physical terminals connected to the system via a serial port,
often using the RS-232 serial interface (see Figure 1.6). These old terminals often had a green or amber screen
and the minimal hardware and logic to send the text typed by the user in the keyboard and display the text
received from the mainframe in the screen. In the mainframe, there was a command-line interpreter or shell.
A shell is a process that interprets commands and that provides an interface to the services of the system.
We must remark that in current systems, we have another interface called Graphical User Interface or
GUI. Of course, we still have the CLI (Command Line Interface) interface. In general, CLI gives you more
control and flexibility than GUI but GUIs are easier to use. GUI requires a graphical server, called X server
in UNIX. Processes launched from the GUI are typically applications that have graphical I/O. For this
graphical I/O, we can use a mouse, a keyboard, a touch screen, etc. On the other hand, when we
exclusively use the CLI, it is not mandatory to have an X server running in the system. Processes launched
from the CLI are commands that have only textual I/O. The I/O of the textual commands is related or
“attached” to a terminal and the terminal is also attached to a shell. Nowadays we have three types of
terminals: Physical terminals, Virtual Consoles and Terminal Emulators. Physical terminals are not very
common today, but all the Linux systems implement virtual consoles and terminal emulators (see Figure
1.7).
On the other hand, if our Linux system has an X graphical server running, users can also access the system
through a GUI. In fact, GUI is the default interface with the system for most desktop Linux distributions. To
access the login manager to the X server, you must type CRL+ALT+F7 in the majority of the Linux systems.
Once you log into the GUI, you can start a terminal emulator (see Figure 1.6(b)). Terminal emulators are also
called pseudo-terminals. To start a pseudo-terminal you can use ALT + F2 and then type gnome-terminal or
xterm. You can also use the main menu: MENU-> Accessories-> Terminal. This will open a gnome-terminal,
which is the default terminal emulator in our Linux distribution (Ubuntu). As you can see in Figure 1.7(b), the
terminal emulator communicates with the shell (Bash) also using a file /dev/pts/X (where X is the number of
pseudo-terminal). In addition, the pseudo-terminal receives and sends data to the X server using the X
protocol.
Regarding the shell, this documentation refers only to Bash (Bourne Again Shell). This is because this
shell is the most widely used one in Linux and includes a complete structured programming language and a
variety of internal functions.
Note. When you open a terminal emulator or log into a virtual console, you will see a line of text that ends
with the dollar sign “$“ and a blinking cursor. Throughout this document, when using “$“ will mean that we
have a terminal that is open and it is ready to receive commands.
Se puede conformar un entorno multiusuario clásico a través de la conexión de varias terminales (estaciones
de diálogo), es decir unidades de pantalla y teclado.
Desde luego, también bajo Linux se pueden conectar terminales a través de los puertos serie. Pero como
delante de un PC normalmente se sienta una sola persona, se ha incorporado la posibilidad de trabajar con
terminales virtuales. Aunque sólo exista una sola unidad de pantalla y teclado, bajo Linux se puede trabajar
como si se dispusiera de varias terminales a la vez. Con la combinación de teclas CRL+ALT+F1... CRL+ALT+F6
se puede alternar entre cada terminal.
1
tty es una abreviatura para “teletyper”, que es otro término para denominar a la terminal
El sistema operativo Linux no se compone solamente de su núcleo o kernel, sino también de una gran
cantidad de programas adicionales necesarios para un uso seguro y confortable del mismo. Debido a que el
sistema operativo es de hecho una herramienta empleada para lograr un propósito (el uso de aplicaciones),
es necesario instalar también programas de usuario, utilidades, etc. La mayoría de los programas para Linux
también son libres o pueden usarse de forma gratuita, por lo tanto, existe la posibilidad de reunir todo este
conjunto de sistema operativo y programas libres en un paquete que se puede usar sin necesidad de licencias.
Todos estos programas podrían descargarse de Internet, pero habría que transferir grandes
cantidades de datos (del orden de varios centenares de Megabytes), por lo que resulta razonable grabar en
CDs o DVDs el sistema operativo Linux junto con todas las aplicaciones.
Estas son las llamadas distribuciones, ofrecidas por varias empresas y que incluyen generalmente un
manual con instrucciones de instalación (cuya calidad y tamaño varía) así como programas de instalación en
ocasiones bastante sofisticados. El precio de estas distribuciones es el resultado de los costos de producción
o confección y de la ayuda para la instalación, que hace posible el uso de Linux para la mayoría de usuarios,
pero no de las tasas de licencia. Comprando una distribución no se adquiere ninguna licencia para Linux, ya
que Linux no la requiere. De esta manera se evita el problema de la piratería informática, ya que una vez
adquirida, una distribución puede instalarse en tantos ordenadores como se desee.
A finales de los años 60, la mayoría de los sistemas operativos estaban diseñados sólo para “trabajar
en modo batch” (proceso por lotes): quien quería ejecutar un programa, introducía un montón de fichas
perforadas o un rollo perforado en un lector y esperaba hasta que el resultado saliera por una impresora. En
el caso de que hubiera un fallo en el programa o de que el resultado obtenido no fuese el deseado, se debían
escribir nuevos rollos perforados, cambiar una o más tarjetas perforadas, leer el montón de nuevo y esperar
otra vez el resultado.
Este procedimiento no sólo era largo, sino también en su gran mayoría ineficiente, así que
rápidamente surgió el deseo de un sistema operativo que permitiese a varios usuarios trabajar
simultáneamente con el mismo sistema. Un primer desarrollo en esta línea fue MULTICS, que permitía trabajar
con el ordenador en base a un diálogo, pero éste estaba todavía fuertemente influenciado por el “trabajo en
modo batch” y era poco transparente y difícil de manejar.
Cuando los laboratorios Bell (una filial de la firma AT&T) suministraron a las universidades, a precio
de costo, la documentación y el texto fuente de UNIX, el sistema empezó a divulgarse rápidamente. La
facilidad de manejo, la casi total disponibilidad del código fuente y la relativa facilidad para ser nuevamente
“portado”, motivó a muchos usuarios y empresas a hacerse partícipes activos en su desarrollo, así que UNIX
alcanzó rápidamente funcionalidad y un alto grado de madurez. Al mismo tiempo, como resultado, surgieron
una serie de derivados de UNIX, de los cuales los más importantes fueron Microsoft XENIX (más tarde SCO-
UNIX) o la Berkeley Software Distribution BSD, desarrollada por la Universidad de California en Berkeley.
En 1983, a través de su empresa filial USL, comenzó AT&T, a comercializar UNIX System V, y proclamó
System V como el estándar de UNIX. Como consecuencia de aquello cambió sustancialmente el esquema de
licencias de UNIX, lo que provocó largos conflictos jurídicos, entre otros con BSD. Al mismo tiempo las disputas
continuas entre los oferentes de UNIX impidieron una estandarización verdadera de la familia de sistemas
operativos UNIX, de forma que, incluso sistemas operativos UNIX modernos, todavía se pueden separar en
aquellos más cercanos a System V o a BSD. Linux intenta combinar lo mejor de ambos mundos.
En la primavera de 1991 comenzó el estudiante finlandés Linus Benedict Torvalds a estudiar de forma
detallada la gestión de memoria de su PC 386. Pocos meses después surgió de sus estudios un “kernel”
rudimentario que, a través de internet, pasó en código fuente a otros interesados en ello.
En el desarrollo del “kernel” regularmente hay dos versiones actuales: la “estable”, que se puede
reconocer por un número par después del primer punto, y la “versión programador” con un número impar.
Las distribuciones de Linux se basan en las versiones “pares”, pero muchas veces se ofrecen “versiones
programador” del “kernel” relativamente actuales, que en ciertos casos se necesitan para la integración de
nuevos componentes “hardware”.
Quien, por ejemplo, quiera escribir un nuevo compilador y para ello disponer de partes del compilador C de
GNU, cuando desee publicarlo, tiene que hacerlo bajo la GPL.
Consecuencias menos dramáticas tiene el empleo de librerías bajo la licencia LGPL. Aquí el “software” puede
ser publicado (vendido) bajo licencias propias. Esto es aplicable a programas desarrollados para Linux que
emplean las librerías estándar (glibc 2.x).
Quien planee producir software, que más tarde desee vender o del cual no quiere que sea publicado el código
fuente, debe asegurarse que:
1. No utilice ningún código fuente, tampoco partes de él, que esté bajo la licencia GPL y 2. No emplee ninguna
librería sujeta a GPL, porque aunque no se utilice explícitamente ningún código fuente de esas librerías, el
“software” desarrollado debe estar bajo GPL.
Puntos esenciales para que una licencia sea aceptada como “Open Source”, son:
• Es posible la transmisión libre.
• El código fuente está disponible.
• Están permitidos programas derivados.
Claramente no “Open Source” son licencias que sí conceden el acceso a las fuentes, pero prohíben transmitir
complementos o mejoras del software (SUN Solaris).
¡Cuidado! Como el usuario root tiene acceso a todos los archivos y comandos que el sistema tiene, ¡nunca
debe trabajar, excepto el administrador del sistema, bajo esta cuenta! ¡El riesgo de dañar el sistema por
equivocación es demasiado grande! Junto al “login” como usuario root, existe la posibilidad de cambiarse a
Si se quiere enviar un único comando como root, se puede añadir a su el parámetro c para llamar al
comando:
1.8.2 Login-Logout
Si un sistema operativo como Linux ofrece la posibilidad de que varios usuarios trabajen simultáneamente,
entonces esos usuarios deben ser diferenciables unos de otros por el sistema, para evitar que, por ejemplo,
la carta personal que un usuario escribe, aparezca por error en la pantalla de otro. Por esa razón, todo el que
trabaje con un computador con Linux debe en primer lugar darse de alta en el sistema e identificarse ante él.
Este acto, que es parte esencial del concepto de seguridad de Linux, se denomina login.
Si el alta ha sido correcta, el sistema da la bienvenida con el mensaje.
Last login: Tue May 18 22:24:43 on tty1
tux@tierra:~ >
2
Introduciendo el comando su se hereda el “shell” (intérprete de comandos) iniciado en el entorno existente.
Sólo a través de la introducción del comando su - el sistema se comporta como si se hubiese dado de alta como root.
Los entornos de escritorio (desktop environments) van más allá del “look & feel“ que el
gestor de ventanas proporcionan al área de trabajo y de la manipulación de ventanas, con
ellos se intenta dar servicio a clientes que tienen un “look & feel” consistente.
El CDE (Common Desktop Environment) era un intento de realizar un entorno de escritorio
uniforme e independiente del proveedor. Pero aún siendo común en los Unix comerciales,
no ha sido aceptado en el ámbito del Linux.
Como alternativa a él, para Linux se ofrecen GNOME y KDE.
El propósito es hacer que estos dos entornos de trabajo sean lo más compatibles posible,
de forma que las aplicaciones desarrolladas para uno funcionen en el otro sin pérdida de
capacidades.
Para poder utilizar el sistema X Window, hay que arrancar por lo menos un servidor X y un
gestor de ventanas.
Se puede arrancar el servidor X: después del “login” del usuario mediante el “script” startx
o a través de un “display manager” (xdm) incluso antes de que el usuario se dé de alta.
Si el sistema Linux está configurado como corresponde, después del arranque del sistema,
aparece el panel de “login” de la interfaz X, en vez de un “login” en una consola virtual.
2.1 Aplicaciones X
En Linux era un gran problema la escasez que había de aplicaciones para el entorno de
trabajo. Eso ya es pasado. Hoy existen:
• Procesadores de texto
• Hojas de cálculo
• Acceso a bases de datos
• Aplicaciones gráficas
• Paquetes de “office”
Del área comercial son aplicaciones conocidas:
• Staroffice, Applixware Office, Wordperfect Office y muchos más.
En el área de “Open Source” también existen aproximaciones prometedoras:
• Gnome Office
• KLyX
También hay cada vez más interés por Linux en el ámbito de las bases de datos, hoy en
día cualquier gran proveedor ofrece una versión. (Oracle, Informix, IBM DB2, Adabas, etc.)
Aplicaciones gráficas. En informática existen dos tipos de gráficos: por un lado los
llamados gráficos de mapas de bits o de píxeles y por otro los gráficos vectoriales. Un
ejemplo de gráfico de mapa de bits puede ser una fotografía que ha sido escaneada,
mientras que los diagramas y dibujos suelen ser gráficos vectoriales.
Un gráfico de mapa de bits está formado por una matriz de filas y columnas. Cuantas más
filas y columnas pueda contener una superficie, mayor es la resolución de la imagen. A
cada punto de la matriz en los gráficos de mapas de bits le corresponde un color. A partir
de una cierta resolución ya es posible reconocer una imagen.
Los gráficos vectoriales están formados por líneas que pueden ser rectas o curvas. Una
línea recta está definida por sus puntos inicial y final, y por el tipo de línea (por ejemplo
gruesa o discontinua). Incluso al observar en aumento la línea de un gráfico vectorial, ésta
se ve siempre como una línea entre dos puntos con un determinado grosor, y no como una
colección de puntos.
2.2 GIMP
El programa gráfico Gimp, de carácter libre, permite editar fotografías escaneadas o
imágenes tomadas de Internet. El nombre Gimp significa “GNU Image Manipulation
Program”.
En el caso de una instalación estándar, Gimp se activa en el menú a través de los puntos
Gráficos Gimp. También puede iniciarse directamente desde la línea de comandos
¬
Después de la pantalla de bienvenida, se abre una ventana con herramientas para dibujar,
recortar y retocar, y una selección de colores, pinceles y patrones. Gimp dispone además
de una gran variedad de impresionantes efectos.
Enlaces de interés:
http://lucas.hispalinux.es/
http://www.hispalinux.es/
On the other hand, the command ps accepts parameters. For example the parameter -u reports the processes
launched by a user. Therefore, if you type:
$ ps -u user1
We obtain a list of all the processes owned by user1. Next, there is a summary of some relevant parameters
of the ps command (for further information, you can type man ps to view the ps manual):
• -A shows all the processes from all the users.
• -u user shows processes of a particular user.
• -f shows extended information.
• -o format the format is a list separated by commas of fields to be displayed.
Example:
$ ps -Ao pid,ppid,state,tname,%cpu,%mem,time,cmd
The preceding command shows the process PID, the PID of parent process, the state of the process, the
associated terminal, the%of CPU and memory consumed by the process, the accumulated CPU time consumed
and the command that was used to launch the process.
On the other hand, the pstree command displays all the system processes within a tree showing the
relationships between processes. The root of the tree is either init or the process with the given PID.
The top command returns a list of processes in a similar way as ps does, except that the information displayed
is updated periodically so we can see the evolution of a process’ state. top also shows additional information
such as memory space occupied by the processes, the memory space occupied by the exchange partition or
swap, the total number of tasks or processes currently running, the number of users, the percentage processor
usage, etc.
Finally, the time command gives us the duration of execution of a particular command.
Example:
$ time ps
PID TTY TIME CMD
7333 pts/0 00:00:00 bash
8037 pts/0 00:00:00 ps
real 0m0.025s
user 0m0.016s
sys 0m0.012s
Real refers to actual elapsed time; User and Sys refer to CPU time used only by the process.
• Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used
by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).
• User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only
actual CPU time used in executing the process. Other processes and time the process spends blocked do not
count towards this figure.
• Sys is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent
in system calls within the kernel, as opposed to library code, which is still running in user-space. Like ’user’,
this is only CPU time used by the process.
Notice that User+Sys will tell you how much actual CPU time your process used. This is across all CPUs, so if
the process has multiple threads it could potentially exceed the wall clock time reported by Real.
3.4 Scripts
Normally shells are interactive. This means that the shell accepts commands from you (via keyboard) and
executes them. But if you use command one by one, then you can store this sequence of commands into a
text file and tell the shell to execute this text file instead of entering the commands. This is known as a shell
script. Another way of defining a shell script is just as a series of command written in plain text file.
Why to write shell scripts?
• Shell script can take input from user, file and output them on screen.
• Useful to create our own commands.
• Save lots of time.
• To automate some task of day today life.
• System Administration part can be also automated.
Example:
The previous script command executes a ps and then after approximately 2 seconds (sleep makes us wait 2
seconds) a pstree command.
To write down a script you can use a text editor (like gedit). To run a script you must give it execution
permissions ($ chmod u+x myscript.sh) and then execute it ($ ./myscript.sh).
Another example script is the classical “Hello world” script.
Using the first script, notice that the bash clones itself to run the commands within the script
3.6 Señales
Si un proceso debe terminar, el “kernel” le envia la señal correspondiente.
Cuando un proceso recibe una señal, • éste puede, si dispone de la opción
correspondiente, capturar la señal y actuar en consecuencia,
• ignora la señal si no dispone de la función necesaria para tratarla,
• Si el “kernel” es el que trata la señal; el proceso finaliza inmediatamente con “SIGKILL”.
La señal “SIGKILL” se debe utilizar con mucho cuidado ya que el sistema operativo cierra
todos los ficheros abiertos, pero los datos que están en el “buffer” no se procesan.
Por ello el estado de los archivos con los que el proceso estaba ejecutando puede ser
incorrecto.
Los programas bien hechos capturan la señal “SIGTERM” y sólo finalizan cuando han
volcado los datos y cerrado todos los archivos.
La mejor posibilidad para acabar con un proceso indeseado es:
1. enviar “SIGTERM”,
2. dejar tiempo para que almacene correctamente los datos y cierre los ficheros abiertos,
3. si todavía sigue el proceso entonces enviar “SIGKILL”.
El comando kill sin opción significa lo mismo que kill -SIGTERM. Las señales se pueden
especificar también numéricamente. A “SIGKILL” le corresponde el número 9. Con kill -l
se obtiene una listado de todas las señales con sus correspondencias numéricas y con
man 7 signal se obtiene una referencia en cuanto a las señales.
Si se arranca el proceso desde la bash en lugar del número de proceso se puede emplear
también el ID del proceso ( por ejemplo kill %4).
A signal is a limited form of inter-process communication. Essentially it is an asynchronous notification sent
to a process. A signal is actually an integer and when a signal is sent to a process, the kernel interrupts the
process’s normal flow of execution and executes the corresponding signal handler. The kill command can be
used to send signals2.
2More technically, the command kill is a wrapper around the system call kill(), which can send signals to processes or groups of processes
in the system, referenced by their process IDs (PIDs) or process group IDs (PGIDs).
The default signal that the kill command sends is the termination signal (SIGTERM), which asks the process for
releasing its resources and exit. The integer and name of signals may change between different
implementations of Unix. Usually, the SIGKILL signal is the number 9 and SIGTERM is 15. In Linux, the most
widely used signals and their corresponding integers are:
• 15 SIGTERM. Calls for the process termination.
• 9 SIGKILL. Ends the process inmediately.
• 2 SIGINT. Is the same signal that occurs when an user in an interactive press Control-C to request
termination.
• 20 SIGTSTP. The same signal produced by Control-Z, stops a process.
• 18 SIGCONT. Resumes a previously suspended process by SIGSTSTP.
The kill command syntax is: kill -signal PID. You can use both the number and the name of the signal:
$ kill -9 30497
$ kill -SIGKILL 30497
In general, signals can be intercepted by processes, that is, processes can provide a special treatment for the
received signal. However, SIGKILL and SIGSTOP are special signals that cannot be captured, that is to say, that
are only seen by the kernel. This provides a safe mechanism to control the execution of processes. SIGKILL
ends the process and SIGSTOP pauses it until a SIGCONT is received.
Unix has also security mechanisms to prevent an unauthorized users from finalizing other user processes.
Basically, a process cannot send a signal to another process if both processes do not belong to the same user.
Obviously, the exception is the user root (superuser), who can send signals to any process in the system.
Finally, another interesting command is killall. This command is used to terminate execution of processes by
name. This is useful when you have multiple instances of a running program.
$ bg
[2]+ xeyes &
$
In general, typping the JID after the command bg will send the process identified by it to background (in the
previous case the command bg 2 could be used as well).
The JID can also be used with the command kill. To do this, we must write a % sign right before the JID to
differentiate it from a PID. For example, we could terminate the job “1” using the command:
$ kill -s SIGTERM %1
Another very common shortcut is Control-c and is used to send a signal to terminate (SIGINT) the process that
is running on foreground. Example:
$ fg 3
xclock
^C
[1] Terminated xeyes
Notice that whenever a new process is run in background, the bash provides us the JID and the PID:
$ xeyes &
[1] 25647
Here, the job has JID=1 and PID=25647.
3.9 Extra
3.9.1 *Priorities: nice
Each Unix process has a priority level ranging from -20 (highest priority) to 19 (lowest priority). A low priority
means that the process will run more slowly or that the process will receive less CPU cycles.
The top command can be used to easily change the priority of running processes. To do this, press ”r“ and
enter the PID of the process that you want change it’s priority. Then, type the new level of priority. We must
take into consideration that only the superuser ”root“ can assign negative priority values.
You can also use nice and renice instead of top. Examples.
$ nice -n 2 xeyes &
[1] 30497
$ nice -n -2 xeyes
nice: cannot set niceness: Permission denied
$ renice -n 8 30497
30497: old priority 2, new priority 8
2.9.2 *Trap: catching signals in scripts
The trap command allows the user to catch signals in bash scripts. If we use this script:
A shell process is a child of a terminal and when we execute a command, the command becomes a child of
the shell.
If the terminal is killed or terminated (without typing exit), a SIGHUP signal (hang up) sent to all the processes
using the terminal (i.e. bash and currently running commands).
$ tty
/dev/pts/1
The table 2.1 summarizes the commands used within this section.
En Linux existen varios runlevels, que definen en qué estado debe funcionar el sistema.
El “runlevel” estándar, en él se arranca el sistema, está definido en el fichero /etc/inittab en
la entrada initdefault. Normalmente suele ser 3 ó 5. De forma alternativa, al arrancar se
puede especificar el “runlevel” deseado (por ejemplo en el “prompt” de GRUB); el “kernel”
transfiere sin modificar al proceso init los parámetros que él mismo no puede evaluar.
Para cambiar posteriormente a otro “runlevel” (nivel) se llama a init con el número del
“runlevel” correspondiente; desde luego este cambio sólo lo puede iniciar el administrador
del sistema.
Por ejemplo, con el comando
tierra:~ # init 1
se llega al “single user mode”, que administra y mantiene el sistema. Una vez que el
administrador del sistema ha terminado su trabajo, mediante
tierra:~ # init 3
puede volver el sistema al “runlevel” normal en el que todos los programas que son
necesarios para el funcionamientro están en ejecución y los usuarios individuales se
pueden dar de alta.
La tabla siguiente presenta los “runlevels” disponibles.
3.10.2 Shutdown/halt
Con el cambio del “runlevel” el sistema tambien se detiene. Linux es muy sensible, como la
mayoría de los sistemas operativos modernos, si se apaga el sistema sin más.
Lo mínimo que puede ocurrir es que se tengan que comprobar y corregir los sistemas de
archivos antes de que el sistema se pueda volver a utilizar.
Junto con el “hardware” correspondiente, Linux puede apagar el ordenador una vez cerrado
el sistema.
Los nombres de los “stop scripts” siempre empiezan por K (kill), los de los “scripts” de arranque por S (start).
Muchos componentes “hardware” están soportados por módulos del “kernel”. Estos
módulos están en el sistema de archivos de Linux y se pueden integrar en el “kernel” según
sea necesario, sin tener que volver a arrancar el computador.
Un módulo cargado se puede desactivar sólo si ya no existen procesos que acceden al
hadware asociado con él o a servicios correspondientes. Si por ejemplo, un USB está
integrado en el sistema de archivos, entonces el módulo de sistemas de archivos sólo se
puede eliminar una vez que el USB se ha retirado del sistema con el comando umount.
Con el comando lsmod se muestra la lista de módulos.
2. Within the same pseudo-terminal, execute ps with the appropriate parameters in order to show the PID,
the terminal and the command of the currently active processes that have been executed from the terminal.
To the same in the second virtual console.
4. Use the pstree command to see the process tree of the system. Which process is the father of pstree? and
its grandfather? and who are the rest of its relatives?
5. Open a gnome-terminal and then open a new “TAB” typing CRL+SHIFT+t. Now open another gnome-
terminal in a new window. Using pstree, you have to comment the relationships between the processes
related to the terminals that we opened.
7. Open three gnome-terminals. These will be noted as t1, t2 and t3. Then, type the following:
t1$ xeyes -geometry 200x200 -center red t2$ xclock &
Comment what you see and also which is the “state” (foreground/background) of each terminal.
8. For each process of the previous applications (xeyes and xclock), try to find out the PID, the execution state,
the tty and the parent PID (PPID). To do so, use the third terminal (t3).
9. Using the third terminal (t3), send a signal to terminate the process xeyes.
10. Type exit in the terminal t2. After that, find out who is the parent process of xclock.
11. Now send a signal to kill the process xclock using its PID.
13. Send a signal from the third terminal to stop the process xclock and then send another signal to let this
process to continue executing. Is the process executing in foreground or in background? Finally, send a signal
to terminate the xclock process.
14. Using the job control, repeat the same steps as before, that is, executing xclock in foreground and then
stopping, resuming and killing. List the commands and the key combinations you have used.
15. Execute the following commands in a pseudo-terminal:
$ xclock &
$ xclock &
$ xeyes &
$ xeyes &
Using the job control set the first xclock in foreground. Then place it back in background. Kill by name the two
xclock processes and then the xeyes processes. List the commands and the key combinations you have used.
16. Create a command line using execution of multiple commands that shows the processes launched from
the terminal, then waits for 3 seconds and finally shows again the processes launched from the terminal.
17. Create a command line using execution of multiple commands that shows the processes launched from
terminal but this execution has to be the result of an erroneous execution of a previous ps command.
18. Discuss the results of the following multiple command executions:
$ sleep || sleep || ls
$ sleep && sleep --help || ls && ps
$ sleep && sleep --help || ls || ps
Exercise2– (*) This exercise deals with additional aspects about processes.
1. Type a command to execute an xeyes application in background with “niceness” (priority) equal to 18. Then,
type a command to view the command, the PID and the priority of the xeyes process that you have just
executed.
2. Create a script that asks for a number and displays the number multiplied by 7. Note. If you use the variable
VAR to read, you can use $[VAR * 7] to display its multiplication.
3. Add signal managment to the previous script so that when the USR1 signal is received, the script prints the
sentence “waiting operand”. Try to send the USR1 signal to the clone Bash executing the script. Tip: to figure
out the PID of the proper Bash, initially launch the script in background.