You are on page 1of 6

Gestión de procesos en GNU/Linux

El siguiente ensayo tratará sobre la importancia y gestión de los procesos a nivel de


software y hardware. Antes de entrar al tema veremos, ¿Qué es GNU/Linux?

¿Qué es GNU/Linux?
GNU es un sistema operativo creado en 1983 por Richard Stallman, este sistema es
mantenido actualmente por la Free Software Foundation. Este sistema operativo está
basado en cómo está construido UNIX y mantiene su compatibilidad con él, la prueba hay
instrucciones de la consola de comandos que son compatibles tanto en UNIX como en
GNU. La principal diferencia entre UNIX y GNU, es que GNU es de software libre.
Cuando se comenzó a trabajar en este sistema operativo también se comenzó a trabajar en
su núcleo llamado hard núcleo que hasta el día de hoy no tiene ninguna versión estable,
todo sistema operativo debe tener un núcleo para poder funcionar, así que decidieron
integrar el núcleo de Linux al sistema operativo GNU.

Linux es un núcleo de sistema desarrollado en 1991 por Linus Torvalds y también está
basado en UNIX. En 1992 GNU y Linux se unen para formar un sistema operativo
funcional con carácter de software libre.

Introducción
“Un sistema operativo es el software encargado de ejercer el control y coordinar el uso del
hardware entre diferentes programas de aplicación y los diferentes usuarios. El sistema
operativo se encarga de crear el vínculo entre los recursos materiales, el usuario y las
aplicaciones (procesador de texto, videojuegos, etcétera).” (Galvin, Silberschatz, Gagne
(2005). Fundamentos de sistemas operativos. McGraw-Hill.)

Partiendo de la definición de un Sistema Operativo, cualquier programa que se ejecuta en


cualquier SO es un proceso que requiere recursos, los cuales son asignados y gestionados
por el núcleo (kernel), cumpliendo así una de las funcionalidades del SO. La buena gestión
de los procesos y una buena multiplexación de los recursos del hardware declaran de los
sistemas operativos un buen rendimiento de los mismos. Es por esto que es importante para
nosotros conocer cómo funciona esa gestión, más exactamente en el SO GNU/Linux.

Cada proceso se representa en el sistema operativo con un bloque de control de proceso


(PCB, Process Control Block). En este PCB se guardan una serie de elementos de
información de los mismos. A su vez cada PCB generado se inserta en la tabla de
procesos.
En Linux, inicialmente, la Tabla de Procesos era un vector de tamaño fijo de
task_strcut<linux/sched.h>, con lo que el número máximo de procesos estaba limitado.
Actualmente, la Tabla de Procesos es realmente una lista doblemente enlazada mediante los
punteros next_task y prev_task.

Estos elementos que conforman el PCB son: el identificador del proceso(PID), el


estado del proceso, registros de CPU (acumuladores, punteros de la pila, registros
índice y registros generales), información de planificación de CPU (prioridad de proceso,
punteros a colas de planificación, etc.), información de gestión de memoria, información
de contabilidad (tiempo de uso de CPU, números de procesos, etc.), información de
estado de dispositivos E/S (lista de archivos abiertos, etc.).

A su vez los estados de ejecución de un proceso Linux son los siguientes:

•En Ejecución (TASK_RUNNING). El proceso es ejecutado por el procesador.


•Listo (TASK_RUNNING). El proceso podría ser ejecutado, pero otro proceso se está
ejecutando en ese momento.
•Interrumpible (TASK_INTERRUPTIBLE). Es un estado de bloqueo, en el cual el
proceso espera un suceso, como la terminación de una operación de entrada/salida,
liberación de un recurso o una señal de otro proceso.
•No interrumpible (TASK_UNINTERRUPTIBLE). Es otro estado de bloqueo. La
diferencia entre éste y el estado Interrumpible es que en un estado No Interrumpible, un
proceso espera directamente en una condición de hardware y, por tanto, no acepta
señales.
•Parado (TASK_STOPPED). El proceso ha sido detenido por una intervención externa
y sólo puede reanudarse por una acción positiva de otro proceso. Por ejemplo, un
proceso puede estar en estado Parado durante la ejecución de un programa de
depuración.
•Zombie (TASK_ZOMBIE). El proceso ha terminado pero, por alguna razón, su
estructura task debe permanecer aún en la tabla de procesos.

Conociendo la información necesaria que emplea el sistema operativo GNU/Linux


referente a los procesos, procedemos a conocer ahora los comandos básicos para la
administración y gestión de estos:

o Comando ps: proporciona un snapshot con información (hora de inicio, consumo


de memoria, consumo de CPU, estado, etc.) de los procesos que se están ejecutando
en el sistema por el usuario actual.
o Comando pstree: Este comando muestra la jerarquía de los procesos mediante una
estructura de árbol. Así podemos ver las relaciones que existen entre los procesos.
Si se especifica el PID de un proceso, el árbol empezará desde ese proceso, de lo
contrario el árbol empezará por el proceso init (PID=1) y mostrará todos los
procesos del sistema. Si se especifica un usuario valido se mostrará la jerarquía de
todos los procesos del usuario.
o Comando kill: Se usa para matar o parar un proceso, funciona dando su ID. El
comando kill permite enviar un mensaje arbitrario a un proceso, o varios, con un
PID igual a pids. El parámetro sigspec es el valor entero de la señal o el nombre de
la señal que enviaremos al proceso.
o Comandos pkill y killall: Estos comandos pueden matar procesos dando el nombre
del mismo. Esta orden es ligeramente diferente a la orden kill por dos motivos; en
primer lugar utiliza el nombre de proceso en lugar del pid, y además le envía la
señal a todos los procesos que tengan el mismo nombre.
o Comando top: Muestra una lista parecida a la del comando “ps”, pero esta se
actualiza en tiempo real.
o Empleando & luego del nombre de un proceso, se logra que este se ejecute en
segundo plano, mientras le asigna un JobsID, la misma función cumple los
comandos CTRL + Z.
o Comando fg + JobsID: Se logra regresar el proceso a primer plano.
o Comando jobs: Muestra en pantalla el JobsID + los procesos que se están ejecutando en
segundo plano.

Cada proceso en Linux tiene un nivel de prioridad que oscila entre -20 (prioridad más
alta) y 20 (prioridad más baja). Cuanto mayor sea el nivel de prioridad, más lentamente
se ejecutará el proceso.

o Comando nice: Brinda prioridad a un proceso antes de ser ejecutado.


o Comando renice: Brinda prioridad a un proceso que se encuentra en ejecución.

Todos estos comandos van acompañados por parámetros que establecen diferentes acciones del
mismo, estos pueden ser vistos empleando el comando man +comando.

A modo de conclusión es importante conocer acerca de la gestión de los procesos tanto a


nivel de hardware como software, porque esto nos da una idea tanto del funcionamiento
interno de los dispositivos que emplean CPU’s, como también del rendimiento de los
mismos.
Process Management in GNU/Linux
The following essay will deal with the importance and management of processes at the
software and hardware level. Before we get down to it, we'll see, What is GNU/Linux?

What is GNU/Linux?

GNU is an operating system created in 1983 by Richard Stallman, currently maintained by


the Free Software Foundation. This operating system is based on how UNIX is built and
maintains its compatibility with it, testing there are command prompt instructions that are
compatible with both UNIX and GNU. The main difference between UNIX and GNU is
that GNU is free software. When they started working on this operating system they also
started working on its kernel called hard kernel which to this day has no stable version,
every operating system must have a kernel in order to work, so they decided to integrate the
Linux kernel to the GNU operating system.

Linux is a system kernel developed in 1991 by Linus Torvalds and is also based on UNIX.
In 1992 GNU and Linux came together to form a functional operating system with a free
software character.

Introduction

"An operating system is the software responsible for controlling and coordinating the use of
hardware between different application programs and different users. The operating system
is responsible for creating the link between the material resources, the user and the
applications (word processor, video games, etc.). (Galvin, Silberschatz, Gagne (2005).
Operating system fundamentals. McGraw-Hill.)

Starting from the definition of an Operating System, any program that runs on any OS is a
process that requires resources, which are assigned and managed by the kernel, thus
fulfilling one of the OS functionalities. Good process management and a good multiplexing
of hardware resources declare that operating systems perform well. This is why it is
important for us to know how this management works, more exactly in the GNU/Linux OS.

Each process is represented in the operating system with a Process Control Block (PCB). A
number of information items are stored on this PCB. In turn, each PCB generated is
inserted into the process table.

In Linux, initially, the Process Table was a fixed size task_strcut<linux/sched.h> vector, so
the maximum number of processes was limited. Currently, the Process Table is actually a
doubly linked list using the next_task and prev_task pointers.
These elements that make up the PCB are: process identifier (PID), process status, CPU
registers (accumulators, stack pointers, index registers and general registers), CPU planning
information (process priority, pointers to planning queues, etc.), memory management
information, accounting information (CPU usage time, process numbers, etc.), I/O device
status information (list of open files, etc.).

In turn, the execution states of a Linux process are as follows:

In Execution (TASK_RUNNING). The process is executed by the processor.

Done (TASK_RUNNING). The process could be executed, but another process is currently
running.

Interruptible (TASK_INTERRUPTIBLE). It is a lock state, in which the process waits for


an event, such as the termination of an input/output operation, the release of a resource or a
signal from another process.

Non-interruptible (TASK_UNINTERRUPTIBLE). It's another blocking state. The


difference between this and the Interruptible state is that in a Non-Interruptible state, a
process waits directly in a hardware condition and therefore does not accept signals.

Unemployed (TASK_STOPPED). The process has been stopped by an external


intervention and can only be resumed by a positive action of another process. For example,
a process may be in a stationary state during the execution of a debugging program.

Zombie (TASK_ZOMBIE). The process is finished but, for some reason, its task structure
must still remain in the process table.

Knowing the necessary information that the GNU/Linux operating system uses regarding
the processes, we now proceed to know the basic commands for the administration and
management of these:

o Ps command: provides a snapshot with information (start time, memory consumption,


CPU consumption, status, etc.) of the processes being executed in the system by the current
user.

o Pstree command: This command shows the hierarchy of the processes through a tree
structure. Thus we can see the relationships that exist between the processes.

If the PID of a process is specified, the tree will start from that process, otherwise the tree
will start from the init process (PID=1) and show all the processes in the system.
Specifying a valid user will display the hierarchy of all user processes.

o Kill command: Used to kill or stop a process, it works by giving its ID. The kill command
allows you to send an arbitrary message to a process, or several processes, with a PID equal
to pids. The sigspec parameter is the integer value of the signal or the name of the signal to
be sent to the process.

o Pkill and killall commands: These commands can kill processes by giving them their
name. This command is slightly different from the kill command for two reasons; it first
uses the process name instead of the pid, and then sends the signal to all processes with the
same name.

o Top command: Displays a list similar to that of the "ps" command, but it is updated in
real time.

o Using & after the name of a process, it is possible to execute it in the background, while
assigning it a JobsID, the same function fulfills the commands CTRL + Z.

o fg + JobsID command: The process is returned to the foreground.

o Jobs command: Displays on the screen the JobsID + the processes that are running in the
background.

Each process on Linux has a priority level ranging from -20 (highest priority) to 20 (lowest
priority). The higher the priority level, the slower the process will run.

o Nice command: Gives priority to a process before it is executed.

o Renice command: Gives priority to an ongoing process.

All these commands are accompanied by parameters that set different actions of the same,
they can be seen using the command common +command.

As a conclusion, it is important to know about the management of the processes both at


hardware and software level, because this gives us an idea of the internal functioning of the
devices that use CPU's, as well as their performance.

You might also like