0% found this document useful (0 votes)
7 views30 pages

Sistema Operativo Linux 2022

The document provides an overview of the GNU/Linux operating system, focusing on its Unix/Linux foundations, resource management, and user interaction. It discusses the kernel's role in managing CPU, memory, and I/O devices, as well as the multi-user and multitasking capabilities of Unix systems. Additionally, it covers memory management techniques such as virtual memory and the different interfaces for user interaction, including command-line and graphical user interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views30 pages

Sistema Operativo Linux 2022

The document provides an overview of the GNU/Linux operating system, focusing on its Unix/Linux foundations, resource management, and user interaction. It discusses the kernel's role in managing CPU, memory, and I/O devices, as well as the multi-user and multitasking capabilities of Unix systems. Additionally, it covers memory management techniques such as virtual memory and the different interfaces for user interaction, including command-line and graphical user interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Sistema Operativo GNU/Linux

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.

1.2 Gestión de Recursos


Today, most deployed OS come either from Microsoft WINDOWS/DOS or from UNIX. We must remark that
UNIX and DOS were initially designed for different purposes. While DOS was developed for rather simple
machines called Personal Computers (PC), UNIX was designed for more powerful machines called Mainframes.
DOS was originally designed to run only a process1 or task at a time (also called mono-process or mono-task)
and to manage only a user (mono-user). On the other hand, UNIX was designed from the very beginning as a
multi-user system. This has numerous advantages, even for a system where only one or two people will be
using it. Security, which is necessary for protection of sensitive information, is built into UNIX at selectable
levels. More importantly, the system was designed also from the very beginning to multi-task. Whether one
user is running several programs or several users are running one program, UNIX systems were capable of
managing the situation. As shown in Figure 1.1, today both type of OS (WINDOWS/UNIX) are capable of
managing multiple users and multiple processes and also both can run over the same type of hardware.
However, we would like to point out that many of these capabilities were present in the first design of UNIX,
while they have been added in WINDOWS.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 1


On the other hand, modern OS can be divided in at least three parts: hardware, kernel and user
applications (also called user space). See Figure 1.2.
1 A process is basically a running program.

Figure 1.1: Origins of Linux.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 2


The Linux Kernel a monolithic hybrid kernel. Drivers and kernel extensions typically execute in a
privileged zone known as “Ring 0” (see again Figure 1.2), with unrestricted access to hardware. Unlike
traditional monolithic kernels, drivers and kernel extensions can be loaded and unloaded easily as modules.
Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the
functionality of the kernel without the need to reboot the system. For example, one type of module is the
device driver, which allows the kernel to access hardware

Figure 1.2: OS Rings.

Figure 1.3: Modular Design.

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).

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 3


The boot loader stage is not absolutely necessary. Certain BIOS can load and pass control to Linux without the use of the loader. Each
2

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.

Figure 1.4: The Linux Boot Process.

• 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 process that generates another process is called parent process.

• The process generated by another process is called child process.

• The processes can be parents and children and both at the same time.

• The root of the processes tree is init.

• Each process has a unique process ID called PID (Process Identifier).

• The PID of init is 1.

1.3 Multiusuario/Multitarea. Memoria Virtual


1.3.1 Multiusuario y Multitarea.

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).

En sistemas de un solo procesador, un sistema multiusuario/multitarea simula la simultaneidad,


mientras que la simultaneidad verdadera sólo se puede producir en un sistema multiprocesador.
Pero también en un sistema con un único procesador se obtienen ventajas a través del sistema multitarea, en
este caso se pueden aprovechar los tiempos de espera. Unix realiza una “multitarea preemptiva”, es decir,

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 4


cada proceso dispone de un tiempo máximo en el cual puede trabajar de forma continuada. Cuando ese
tiempo expira, el sistema operativo le retira la disponibilidad del procesador y se la traspasa a otro proceso
que esté dispuesto para la ejecución.

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.

1.3.2 Memoria Virtual

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 5


Figura 1.5: Espacio de direcciones virtuales

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.

Hoy en día la gestión virtual de la memoria se aprovecha ya al cargar un programa.


Se crea una imágen virtual del programa con sus instrucciones ejecutables, sus datos constantes, sus datos
variables y la pila de ejecución (“stack”), a la que en primer lugar no se asocia memoria real. Al arrancar el
proceso entonces se cargan siempre las páginas que se necesitan en su momento. Desde luego el archivo del
programa en el disco duro no se debe modificar, por lo cual las instrucciones y los datos constantes están
protegidos contra la sobreescritura (lo que también es una protección contra fallos del programa).

Esto puede acelerar el arranque de programas grandes.


En los procesadores x86 el proceso de representación es de dos niveles. La dirección “virtual” se reparte en
tres componentes. La primera parte determina, a través de una tabla, la dirección de otra tabla. La segunda
determina el número verdadero de la página en esa tabla y la tercera parte accede a la memoria dentro de
aquella página.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 6


1.4 Interacción con el usuario. Terminales reales y virtuales
1.4.1 interacción con el usuario

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.

Figure 1.6: Old Physical Terminals

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).

Figure 1.7: Linux Terminals

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 7


If we use virtual consoles to interact with our Linux system, we do not require to start an X server within
the system. Virtual consoles just manage text and they can emulate the behavior of several physical terminals.
As in general, the user only has a single screen and keyboard, the different virtual consoles are accessed using
different key combinations. By default, when Linux boots it starts six virtual consoles which can be accessed
with CRL+ALT+F1 ... CRL+ALT+F6. As shown in Figure 1.7(a), there is a process called getty which manages the
first stage of the virtual console. Once you log into the system (you enter your user name login and password),
the management is now passed to a process called login, which starts a shell (Bash in our case). The
communication between the virtual console and the shell is not performed using any physical media but using
a special file: /dev/ttyX (where X is the number of virtual console).

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.

1.4.2 Terminales reales y virtuales.

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.

• Alterne con las teclas entre los diferentes terminales virtuales.


Se puede reconocer el terminal en el que actualmente se encuentra, mediante la numeración de las tty (tty1
– tty6)1.

1
tty es una abreviatura para “teletyper”, que es otro término para denominar a la terminal

1.5 Implementaciones y Distribuciones de Linux


UNIX is now more a philosophy than a particular OS. UNIX has led to many implementations, that is to say,
different UNIX-style operating systems. Some of these implementations are supported/developed by private
companies like Solaris of Sun/Oracle, AIX of IBM, SCO of Unisys, IRIX of SGI or Mac OS of Apple, Android of
Google, etc. Other implementations of Unix as “ Linux” or “FreeBSD” are not commercial and they are
supported/developed by the open source community.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 8


In the context of Linux, we also have several distributions, which are specific forms of packaging and
distributing Linux (Kernel) and its applications. These distributions include Debian, Red Hat and some derivate
of these like Fedora, Ubuntu, Linux Mint, SuSE, etc.

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.

1.6 Desarrollo histórico de Unix/Linux


En los años ochenta y al comienzo de los noventa hubo - aparte de los supercomputadores - una clara
distinción entre costosos servidores para todo un departamento (normalmente con Unix como sistema
operativo y con aplicación comercial) y pequeños computadores personales (PC), fabricados en grandes
cantidades a un precio más asequible. Para unir las ventajas de las máquinas Unix (estabilidad, alta potencia)
con las de los PCs (hardware de precio más reducido), se llevaron a cabo en los años ochenta varios intentos
de desarrollar un sistema del estilo Unix para PCs. Fue en el año 1991 (el procesador 80386 de Intel ya estaba
entonces disponible para PCs) cuando el estudiante finlandés Linus Torvalds publicó en Internet su propia
propuesta para un sistema operativo al estilo Unix que se denominó, de manera semejante a su creador,
Linux. La clave para el éxito de Linux fue su libre disponibilidad desde sus comienzos. De este modo fue posible
que programadores interesados de todo el mundo participaran en su desarrollo. Gracias a la publicación del
código fuente y al tipo de licencia, nadie puede obtener derechos de autor sobre Linux, garantizando así
también en el futuro que no se cobren licencias para el uso del sistema operativo (naturalmente esto no
incluye los programas comerciales que se puedan usar bajo Linux).

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 9


En 1969 uno de los programadores de MULTICS, Ken Thompson, comenzó a crear un sistema
operativo que, aparte de un manejo basado en diálogos, debería mostrar una alta funcionalidad y sencillez
estructural. La primera versión de UNIX fue escrita en ensamblador, un lenguaje de programación muy
cercano al “hardware”. Para ser más independientes del “hardware” en siguientes desarrollos, a partir de
1971, Dennis Ritchie reescribió UNIX en el lenguaje de programación C.

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.

Figure 1.8: Correo de Linus Torvalds

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 10


Linux pasó a ser un proyecto que abarca a muchas personas y en el que el desarrollo del “kernel” (“kernel de
Linux”) está todavía coordinado por Linus Torvalds. La totalidad de los cambios en el “kernel” son integrados
por él. De otros componentes del sistema (utilidades de “shell”, programas de red e implantaciones del
“kernel” para procesadores no Intel) se ocupan otras personas o grupos.

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”.

1.7 Licencias y copyright


La discusión acerca de Linux vuelve a girar siempre alrededor de la libre disponibilidad del sistema. La forma
de licencia utilizada por Linux es la GPL (GNU General Public License). Con ella se asegura que este sistema
pueda ser desarrollado en el futuro independientemente de las personas o empresas. En Linux nadie puede
adquirir derechos que impidan a otros utilizar o desarrollar el sistema. En la discusión suelen equipararse las
licencias “Dominio público” con las “Open Source”. Este malentendido puede provocar consecuencias legales
al transmitir o vender alguna licencia de Software. Por ello, la situación de las licencias debe ser
cuidadosamente aclarada. La licencia de Berkeley prácticamente no limita la utilización del código fuente.
Cuando se utiliza código sólo se debe indicar el origen del mismo. No existe ninguna obligación de transmitir
el código fuente, modificado o no.

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).

1.8 Usuario root.Login-Logout


1.8.1 Usuario root
Como en todos los sistemas Unix, existe en Linux un usuario privilegiado, el súper usuario, el cual es conocido
como root.

¡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

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 11


usuario root, aunque el usuario se haya inscrito como usuario normal. Para ello es preciso utilizar el comando
su -2. Tras la introducción del comando, el sistema pregunta por la contraseña para root. Si la contraseña es
correcta, se modifica también el “prompt”:

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:~ >

El sistema ya esta preparado para aceptar y ejecutar comandos

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 12


2. Interfaz gráfica de usuario
La interfaz gráfica en Linux y UNIX se denomina sistema X Window o X Window System (o también
simplemente X o X11).
El componente más importante es el servidor X, que controla la pantalla, el teclado y el
mouse. El programa del servidor X proporciona una serie de funciones gráficas de carácter
básico como son la visualización de texto en pantalla o el dibujo de líneas. Todos los
programas que necesitan un entorno gráfico se apoyan en estas prestaciones del servidor
X. Estos programas se denominan clientes X o aplicaciones X.
Otro componente muy importante del sistema X Window es el gestor de ventanas
(ingl. windowmanager). Se trata de un programa independiente que administra las
ventanas.
También se ocupa de la representación y el comportamiento del mouse y las ventanas del
programa. El gestor de ventanas y el servidor X intercambian información, por ejemplo a la
hora de abrir una nueva ventana.
La ventaja de la independencia existente entre servidor X y gestor de ventanas radica en
que el gestor puede ser adaptado al gusto de cada usuario. Existe una variedad de gestores
de ventanas, entre ellos Fvwm2 o Window Maker.
Estos son algunos de los entornos de escritorio: GNOME, KDE, XFCE, GNOME-UNITY
Los gestores de ventanas, permiten controlar las ventanas gráficas, posición, movimiento,
tamaño, apariencia y sus funcionalidades ó vínculos con el teclado y el mouse. Algunos
gestores de ventanas: Matacity (GNOME), compiz (GNOME-Unity, Kwin (KDE).
El gestor de ventanas puede seleccionarse en la máscara de registro del computador
mediante el botón Tipo de sesión.
El sistema XWindow se creó en 1984 en el MIT (Massachusetts Institute of Technology).
El objetivo de su desarrollo era poder ejecutar aplicaciones gráficas en toda la red
independientemente del “hardware”. Es decir, con el sistema X Window es posible mostrar
una aplicación gráfica en una pantalla cualquiera y manejarla sin que esa aplicación tenga
que funcionar en el computador al que corresponde la pantalla. La base para esta
separación es una componente del servidor (servidor X) y la propia aplicación (cliente X),
que se comunican entre sí a través del protocolo X.
Servidor X – El servidor X controla la pantalla gráfica, correspondiendo más o menos a lo
que en otros sistemas se conoce como “driver” gráfico. Además gestiona los dispositivos
de entrada, como el teclado y el mouse, y transfiere sus acciones al cliente X. Sin embargo
el servidor X aún no tiene nada que ver con el aspecto de las ventanas y del área de trabajo;
esa es tarea del gestor de ventanas.
Cliente X – El cliente X es una aplicación gráfica que utiliza los servicios del servidor X para
recibir de él las acciones del teclado y del mouse e imprimir a través de él su propia salida
en la pantalla.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 13


Figura 2.1: Clientes X y servidor X se ejecutan en distintos computadores

Como se puede ver en la imagen anterior, el servidor X funciona en el computador tierra,


mientras que en sol y venus lo hacen los clientes X. La presentación de los clientes X sin
embargo, se lleva a cabo a través del servidor X en tierra.
Cuando se trabaja con varios programas simultáneamente suele ocurrir que la pantalla se
llena de ventanas, ofreciendo un aspecto un tanto confuso. Linux nos permite cambiar a
otro escritorio virtual, poniendo así un poco de orden en el caos.

En un computador pueden funcionar varios servidores X, y a su vez, en ellos pueden


estar conectadas varias pantallas. Al cliente X que está funcionando en una máquina
distinta a la del servidor X hay que informarle para que sepa con qué teclado, mouse y
pantalla debe comunicarse. La sintáxis del nombre de “display” es:
computador: Número de “display”.Número de pantalla
Nombre del Computador (o dirección de red) del computador en el que está conectada la
pantalla. Si no se especifica el nombre del computador, se utiliza la pantalla local.
Número de “display” – Indica el número de “display”. Un “display” es un elemento que
consta de un monitor (o varios monitores), un teclado y un mouse. Normalmente el número
de “display” es 0, ya que normalmente el computador sólo tiene un “display”. Pero los
sistemas multiusario pueden fácilmente tener varios “display”, que se numeran empezando
por 0.

Si se quiere arrancar un segundo servidor X en un computador que posee un solo “display”,


entonces se debe emplear otro valor para el número de “display”, por ejemplo 1.
Número de pantalla – Los “displays” pueden tener más de un monitor como unidad de
presentación. Este número indica en qué monitor debe el cliente X realizar su trabajo.
Normalmente el nombre del “display” se especifica en la variable de entorno $DISPLAY,
pero también se puede especificar para un cliente X, con la opción -display
nombre_de_display.
Las propiedades del área de trabajo (escritorio, desktop) y las ventanas (posición, aspecto,
modos de cambio), es decir su “look & feel”, los determina el gestor de ventanas. Es el que
facilita al usuario el manejo, tamaño y posición de las ventanas, determinando además el
aspecto y el comportamiento de los menús de selección del escritorio.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 14


El gestor de ventanas no es más que un cliente X, es decir, no tiene que ejecutarse en el
mismo computador en el que tiene lugar la presentación, además el sistema X Window no
está predeterminado para ningún gestor de ventanas específico y por ello, para ningún “look
& feel” determinado.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 15


Esto se entenderá mejor tomando como ejemplo una línea en la pantalla (véase la figura
2.2 en la página siguiente): al observar la línea bajo una lupa, pueden reconocerse
claramente cada uno de los puntos cuadrados (píxel) que la componen.
Por lo general, los archivos de gráficos de mapas de bits requieren mucha memoria, ya que
es necesario guardar un valor para cada punto de la matriz, incluso cuando el punto en
cuestión no sea de ningún color y simplemente deje ver el fondo.

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.

Un gráfico vectorial puede convertirse fácilmente en un gráfico de mapa de bits. Sin


embargo, el procedimiento inverso sólo puede llevarse a cabo a costa de gran capacidad
de cálculo y pérdida de calidad.

Figura 2.2: Una línea está formada por 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
¬

introduciendo el comando gimp.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 16


2.3 Entorno de Escritorio GNOME
En realidad GNOME no es un gestor de ventanas, sino un entorno de escritorio. Mientras
que KDE incluye un gestor de ventanas propio, kfm, GNOME no está vinculado a ningún
gestor de ventanas sino que, a través del centro de control de GNOME, puede enlazarse
con cualquier gestor de ventanas. Por defecto, GNOME se inicia con un gestor de ventanas
llamado Sawfish.
Al igual que KDE, GNOME soporta la función Drag & Drop o “arrastrar y soltar” e incluye
muchos programas adaptados a GNOME. En Europa, KDE está más extendido que
GNOME, mientras que en Estados Unidos sucede a la inversa.
El aspecto y funciones de GNOME pueden modificarse fácil y cómodamente en el centro
de control de GNOME. Éste ofrece también la posibilidad de seleccionar otros gestores de
ventanas.

Enlaces de interés:
http://lucas.hispalinux.es/
http://www.hispalinux.es/

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 17


3. Procesos
El programa básico en un ordenador es el sistema operativo, cuyo componente central se
denomina kernel. Además se ejecutan una serie de programas de aplicación a los que
también se llama procesos. Cuando un proceso se inicia, recibe del kernel un número de
identificación llamado número de proceso o process ID.
Los procesos por sí mismos no tienen acceso directo al hardware, sino que han de solicitar
al kernel los recursos del sistema que necesitan, como memoria o tiempo de cálculo. De
esta forma, el kernel se encarga de que, por ejemplo, ningún programa use memoria ya
ocupada.
Linux es un sistema operativo multitarea, lo que significa que puede ejecutar varios
procesos simultáneamente. De hecho, no se ejecutan todos en el mismo momento, sino
sólo aparentemente: una parte muy importante del kernel, el planificador o scheduler,
cambia varias veces por segundo entre los distintos procesos, asignando a cada uno un
tiempo de cálculo. El usuario no nota estos cambios, sin embargo, cuando hay muchos
procesos en ejecución, ésta se ralentiza.
Linux es un sistema operativo multitarea, lo que significa que puede ejecutar varios
procesos simultáneamente. De hecho, no se ejecutan todos en el mismo momento, sino
sólo aparentemente: una parte muy importante del kernel, el planificador o scheduler,
cambia varias veces por segundo entre los distintos procesos, asignando a cada uno un
tiempo de cálculo. El usuario no nota estos cambios, sin embargo, cuando hay muchos
procesos en ejecución, ésta se ralentiza.
Los procesos pueden tener diferentes estados, por ejemplo:
• Activo (running)
El proceso está realizando una determinada tarea.
• Durmiente (sleeping)
El proceso está a la espera de un determinado evento, como que el usuario pulse
una tecla o la finalización de un subprograma.
• Detenido (stopped)
El proceso ha sido detenido por una intervención del usuario.
Con el mecanismo de control de “jobs” de la bash se puede llevar a cabo una parte de la
administración de procesos. No están sujetos a este control los procesos que se lanzan en
segundo plano y los que están ejecutándose al darse el usuario de alta en el sistema.
Estos procesos tampoco están conectados con la terminal.
Unix enumera los procesos. El proceso init tiene siempre el número 1. Este proceso arranca
todos los demás. El número máximo de procesos es 32767, cuando se alcanza este número
se vuelve a contar otra vez desde el principio, desde el primer número que no se ha
utilizado.
Si el usuario desea ver todos sus procesos debe proceder del siguiente modo:
tux@tierra:~ > ps x
PID TTY STAT TIME COMMAND
1301 tty2 R 0:00 -tcsh
1344 ? S 0:00 sleep 99
1348 tty2 R 0:00 ps x
tux@tierra:~ >
Ahora el usuario ve todos sus procesos; la entrada de ps sin la opción x le hubiese mostrado
lo siguiente:
tux@tierra:~ > ps
PID TTY TIME CMD
1301 tty2 00:00:00 -tcsh
1349 tty2 00:00:00 ps
tux@tierra:~ >

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 18


El proceso 1344 no es visible porque no está conectado a una terminal.
Otras opciones controlan el contenido de las informaciones mostradas:
• w Wrap – no se cortan los líneas demasiado largas, sino que se presentan en varias líneas.
• l Long – más información sobre los procesos.
• u User – propietario del proceso.
Qué significan las informaciones mostradas:
PID – el ID (número de identificación) del proceso
• TTY – el número de la terminal que controla el proceso
• PRI – prioridad
• NI – “nice” – influye en la adaptación dinámica de prioridades
• SIZE – la cantidad la memoria que ocupa el programa
• STAT – estado actual del proceso
– R – “runnable” – puede trabajar
– S – “sleeping” – espera algún suceso externo (por ejemplo, la llegada de datos)
– D – “uninterruptible sleep” – como “S”, el proceso de momento no puede finalizarse
– T – “suspended” – suspendido
– Z – “zombie” – el proceso se ha finalizado pero no se ha pedido información acerca de su
fin.
– TIME – el tiempo de cálculo utilizado
– COMMAND – el nombre del comando

3.1 The man command


The man command shows the “manual” of other commands. Example:
$ man ps
If you type this, you will get the manual for the command “ps”. Once in the help environment, you can use
the arrow keys or AvPag/RePaq to go up and down. To search for text xxx, you can type /xxx. Then, to go to
the next and previous matches you can press keys n and p respectively. Finally, you can use q to exit the
manual.

3.2 Working with the terminal


Bash keeps the command line history. The history can be seen with the command history. You can also press
the up/down arrow to scroll back and forth through your command history. You can also retype a command
of the history using !number.
On the other hand, the bash provides another useful feature called command line completion (also called tab
completion). This is a common feature of bash and other command line interpreters. When pressing the tab,
bash automatically fills in partially typed commands.
Finally, X servers provide a “cut and paste” mechanism. You can easily copy and paste between pseudo-
terminals using nothing but your mouse only. Most Linux distros are configured the click of a middle mouse
button as paste operation. All you have to do is select text, move your most to another window and hit the
middle mouse button. If you have a scroll wheel, just press on it to past the text. If you see only two buttons,
just hit both button simultaneously i.e. you can emulate a third, "middle" button by pressing both mouse
buttons simultaneously.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 19


3.3 Viewing the processes
The command ps provides information about the processes running on the system. If we open a terminal and
type ps, we obtain a list of running processes. In particular, those launched from the terminal.
$ ps
PID TTY TIME CMD
21380 pts/3 00:00:00 bash
21426 pts/3 00:00:00 ps
Let’s see what these columns mean:
The first column is the process identifier.
The second column is the associated terminal1. In the previous example is the pseudo-terminal 3. A question
mark (?) in this column means that the process is not associated with a terminal.
The third column shows the total amount of time that the process has been running.
The fourth column is the name of the process.
In the example above, we see that two processes have been launched from the terminal: the bash, which is
the shell, and command ps itself. Figure 3.1 shows a scheme of the relationships of all the processes involved
when we type a command in a pseudo-terminal.

Figure 3.1: Processes related with a pseudo-terminal.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 20


1The terminal can also be viewed with the tty 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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 21


As you can observe, the script begins with a line that starts with “#!”. This is the path to the shell that will
execute the script. In general, you can ignore this line (as we did in our previous example) and then the script
is executed by the default shell. However, it is considered good practice to always include it in scripts. In our
case, we will build scripts always for the bash.
As you can see to write to the terminal we can use the echo command. Finally, you can also observe that text
lines (except the first one) after the sign “#” are interpreted as comments.
Next, we assign execution permission and execute the script:
$ chmod u+x myscript.sh
$./myscript.sh
Hello world
Finally, in a script you can also read text typed by the user in the terminal. To do so, you can use the read
command. For example, try:

Using the first script, notice that the bash clones itself to run the commands within the script

3.5 Running in foreground/background


By default, the bash executes commands interactively, i.e., the user enters a command, the bash marks it to
be executed, waits for the output and once concluded returns the control to the user, so he can execute a
new command. This type of execution is also called foreground. For example,
$ sleep 5
The command simply makes us wait 5 seconds and then terminates. While running a command in foreground
we cannot run any other commands.
Bash also let us run commands non-interactively or in background. To do so, we must use the ampersand
symbol (&) at the end of the command line. Example:
$ sleep 5 &
Whether a process is running in foreground or background, its output goes to its attached terminal. However,
a process cannot use the input of its attached terminal while in background.

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”.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 22


tierra:~ # kill -SIGTERM 1810
tierra:~ # kill -SIGKILL 1810

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.

3.7 Job Control


Job control refers to the bash feature of managing processes as jobs. For this purpose, bash provides the
commands “jobs”, “fg”, “bg” and the hot keys Control-z and Control-c.
The command jobs displays a list of processes launched from a specific instance of bash. Each instance of bash
considers that it has launched processes as jobs. Each job is assigned an identifier called a JID (Job Identifier).
Let’s see how the job control works using some examples and a couple of graphic applications: xeyes and
xclock. The application xeyes shows eyes that follow the mouse movement, while xclock displays a clock in
the screen.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 23


$ xeyes &
$ xeyes &
$ xclock &
$
The previous commands run 2 processes or instances of the application xeyes and an instance of xclock. To
see their JIDs, type:
$ jobs
[1] Running xeyes &
[2]- Running xeyes &
[3]+ Running xclock &
$
In this case we can observe that the JIDs are 1, 2 and 3 respectively. Using the JID, we can make a job to run
in foreground. The command is fg. The following command brings to foreground job 2.
$ fg 2
xeyes
On the other hand, the combination of keys Control-z sends a stop signal (SIGSTOP) to the process that is
running on foreground. Following the example above, we had a job xeyes in the foreground, so if you type
control-z the process will be stopped.
$ fg 2
xeyes
^Z
[2]+ Stopped xeyes
$ jobs
[1] Running xeyes &
[2]- Running xclock &
[3]+ Stopped xeyes
$
To resume the process that we just stopped, type the command bg:

$ 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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 24


3.8 Running multiple commands
The commands can be run in some different ways. In general, the command returns 0 if successfully executed
and positive values (usually 1) if an error occurred. To see the exit status type echo $?. Try:
$ ps -ñ
$ echo $?
$ ps
$ echo $?
There are also different ways of executing commands:
$ command the command runs in the foreground.
$ command1 & command2 & ... using & one or more commands will run in background.
$ command1; command2 ... sequencial running.
$ command1 && command2 && ... command2 is executed if and only if command1 exits successfully (exit
status is 0) and so on.
$ command1 || command2 || ... command2 is executed if command1 fails execution. That is to say, if
command1 has an exit status > 0 or if command1 has not been executed.

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:

Try to press CTRL+c.

3.9.2 *The terminal and its associated signals

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

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 25


$ echo $PPID
11587
$ xeyes &
[1] 11646
$ ps
PID TTY TIME CMD
11592 pts/1 00:00:00 bash
11646 pts/1 00:00:02 xeyes
11706 pts/1 00:00:00 ps
If you close the terminal from the GUI, or if you type the following from another terminal:
$ kill -TERM 11587
You will observe that the xeyes process also dies.
However, if you type exit in a shell with a process in background, you will notice that the process does not die
but it becomes orphan and Init is assigned as its new parent process.
There is a shell utility called nohup, which can be used as a wrapper to start a program and make it immune
to SIGHUP. Also the output is stored in a file called nohup.out in the directory from which we invoked the
command or application. Try to run the previous example with $ nohup xeyes &.
On the other hand, if there is an attempt to read from a process that is in background, the process will receive
a SIGTTIN signal. If not captured, this signal suspends the process.
Finally, if you try to exit a bash while there are stopped jobs, it will alert us. Then the command jobs can be
used to inspect the state of all those jobs. If exit is typed again, the warning message is no longer shown and
all suspended tasks are terminated.

3.9.3 *States of a process

A process might be in several states:


• Ready (R) - A process is ready to run. Just waiting for receiving CPU cycles.
• Running (O) - Only one of the ready processes may be running at a time (for uniprocessor machine).
• Suspended (S) - A process is suspended if it is waiting for something to happen, for instance, if it is waiting
for a signal from hardware. When the reason for suspension goes away, the process becomes Ready.
• Stopped (T) - A stopped process is also outside the allocation of CPU, but not because it is suspended waiting
for some event.
• Zombie (Z) - A zombie process or defunct is a process that has completed execution but still has an entry in
the process table. Entries in the process table allow a parent to end its children correctly. Usually the parent
receives a SIGCHLD signal indicating that one of its children has died. Zombies running for too long may point
out a problem in the parent source code, since the parent is not correctly finishing its children.
Note. A zombie process is not like an “orphan” process. An orphan process is a process that has lost its father
during its execution. When processes are “ orphaned”, they are adopted by “ Init.”

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 26


3.9.5 Command Summary

The table 2.1 summarizes the commands used within this section.

EJERCICIO: Monitorear y finalizar procesos


1. Inicie varios procesos y observe con el comando ps la lista de los procesos (utilice por
razones de sencillez el comando sleep. Con un número especificado como parámetro, este
comando espera tantos segundos como el número especificado.).
2. Finalice algún proceso con kill.

3.10 El programa init


El programa /sbin/init es el responsable de la correcta inicialización del sistema; se puede
decir que es “el padre de todos los procesos” en el sistema.
Entre todos los programas, init tiene un papel especial: init es lanzado directamente por el
“kernel” y es inmune a la señal 9, con la que normalmente se puede “matar” cualquier
proceso. Todos los demás procesos los lanza el propio init o alguno de sus procesos hijos.
init se configura mediante el fichero /etc/inittab; aquí se definen los llamados “runlevels”, o
niveles de ejecución, y se determina qué es lo que tiene que pasar en cada nivel concreto.
Dependiendo de las entradas en /etc/inittab, init lanza “scripts” distintos, que por razones
de claridad, están ubicados en el directorio /etc/init.d.
Todo el proceso de arranque del sistema – y desde luego también el proceso de parada -
es controlado exclusivamente por init; de esta forma se puede ver el “kernel” como un
proceso en segundo plano, el cual tiene la tarea de administrar los procesos arrancados,
proporcionarles el tiempo de cálculo, y permitir y controlar su acceso al “hardware”.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 27


3.10.1 Los run level

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.

Lo que significa que el sistema puede pararse mediante,


tierra:~ # init 0
y respectivamente se puede volver a arrancar mediante,
tierra:~ # init 6

Si se ha configurado correctamente el sistema X Window y se desea que el usuario se dé


de alta en el sistema directamente en la interfaz gráfica,
tierra:~ # init 5

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 28


Con los comandos halt y poweroff se consigue el cierre súbito y controlado, si es posible,
este último comando apaga el aparato. Se puede rearrancar otra vez el sistema con reboot.
Todos estos comandos utilizan el comando shutdown.
shutdown permite fijar una hora en la que debe realizarse el cierre o arranque del sistema.
El tiempo puede ser especificado de forma absoluta o relativa:
shutdown +m – m es la cantidad de minutos, 0 significa ahora mismo, shutdown hh:mm
– hh representa la hora y mm los minutos dentro de la hora.
Como argumento opcional shutdown puede tener un mensaje de atención especial:
shutdown +5 el nuevo disco duro está

Se puede cancelar un “shutdown” programado con:


shutdown -c

Los nombres de los “stop scripts” siempre empiezan por K (kill), los de los “scripts” de arranque por S (start).

3.10.3 El Kernel y módulos de kernel

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.

3.11 Primera Práctica calificada


Exercise1– In this exercise you will practice with process execution and signals.
1. Open a pseudo-terminal and execute the command to see the manual of ps. Once in the manual of the ps
command, search and count the number of times that appears the pattern ppid.

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.

3. Execute the following commands:


$ ps -o pid,command
$ ps -o pid,cmd
Comment the differences between the options: cmd and command.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 29


6. Type ALT+F2 and then xterm. Notice that this sequence opens another type of terminal. Repeat the same
sequence to open a new xterm. Now, view the process tree and comment the differences with respect to the
results of the previous case of gnome terminals.

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.

12. Execute an xclock in foreground in the first terminal t1.

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.

M.Sc.Ing. Gumercindo BARTRA GARDINI Página 30

You might also like