Operating Systems User Interfaces

422
Operating Systems User Interfaces M.C. Juan Carlos Olivares Rojas Operating Systems [email protected] February, 2009

description

Operating Systems User Interfaces. M.C. Juan Carlos Olivares Rojas. Operating Systems [email protected] February, 2009. Outline. CLI (Command Line Interface) DOS Basic Commands Windows NT Basic Commands *X Systems Graphical User Interfaces - PowerPoint PPT Presentation

Transcript of Operating Systems User Interfaces

Page 1: Operating Systems User Interfaces

Operating Systems User Interfaces

M.C. Juan Carlos Olivares Rojas

Operating [email protected]

February, 2009

Page 2: Operating Systems User Interfaces

Outline• CLI (Command Line Interface)– DOS Basic Commands– Windows NT Basic Commands– *X Systems

• Graphical User Interfaces– Basic Operation of Wndows Systems at Windows,

*X and MAC-OS

• New Trends in User Interface of Operating Systems

Page 3: Operating Systems User Interfaces

Objective• The student will know and apply basic

commands in diferent OS.

• The student will know the Basic Concepts about Graphical User Interfaces and the trends in user interfaces.

Page 4: Operating Systems User Interfaces

DOS• DOS (Disk Operating System, Sistema

Operativo de Disco) fue el primer sistema operativo para las IBM-PC.

• Desarrollado por la compañía Microsoft en 1981 se vendía junto con la computadora personal de IBM, recibiendo IBM las regalías.

• Es un sistema operativo compacto con muchas limitaciones actualmente, pero funcional.

Page 5: Operating Systems User Interfaces

DOS

• Es un sistema operativo monotarea, multiusuario capaz de ejecutarse a través de un disco flexible (recordar que las primeras PCs no tenían disco duro)

• Es un sistema operativo basado en línea de comandos, por lo que el usuario para poder trabajar con la máquina ocupa saber comandos.

Page 6: Operating Systems User Interfaces

DOS

• El sistema operativo cuenta con comandos que son reconocidos como válidos los cuales se pueden encontrar en el proceso principal o en utilerías.

• Cualquier programa tiene que acceder al sistema operativo para el manejo de los recursos, pero DOS es muy tolerante en el acceso al hardware

Page 7: Operating Systems User Interfaces

DOS

• La administración de procesos es simple, dado que sólo existe una tarea activa.

• El sistema puede manejar interrupciones y ejecutar otra tarea.

• Los procesos pueden ser .com o .exe, donde los primeros sólo ocupan un segmento.

Page 8: Operating Systems User Interfaces

DOS

• La memoria está administrada a través de un esquema de segmentación. Cada segmento tiene un tamaño de 64 KB. El sistema operativo sólo puede acceder a 640 KB.

• El microprocesador 8086 puede direccionar hata un MB de memoria RAM por lo que queda una zona de memoria alta entre 640 KB y 1 MB llamada memoria alta.

Page 9: Operating Systems User Interfaces

DOS

• El sistema no puede acceder a más de 1 MB de RAM, por lo que se encuentra limitado en el número de programas que se mantiene en memoria.

• A la memoria entre un 640 KB y 1 MB se le llama memoria expandida, después del 1 MB y superior se le llama memoria extendida. Esta limitante motivo el surgimiento de Windows.

Page 10: Operating Systems User Interfaces

DOS

• La administración de Entrada/Salida (Periféricos) es sencilla ya que no hay compartición de los mismos. Cada programa necesita instalar el controlador del dispositivo para que pueda trabajar de forma eficiente.

• La administración de archivos se basa en un esquema jerárquico tipo árbol, en donde la raíz corresponda cada letra de una unidad de almacenamiento.

Page 11: Operating Systems User Interfaces

DOS

• Los archivos deben tener un nombre máximo de 8 caracteres seguidos de una extensión de máximo tres caracteres.

• Las nuevas versiones de DOS permiten nombres de archivos más grande.

• Los directorios permiten administrar de forma eficiente los archivos. Los directorios son contenedores de archivos.

Page 12: Operating Systems User Interfaces

DOS• Al encender la computadora, el DOS carga dos

archivos fundamentales: autoexec.bat y config.sys

• Autoexec.bat es un archivo por lotes que contiene algunos comandos para inicializar el sistema. Config.sys es un archivo que permite cargar dispositivos al sistema y otras configuraciones.

• Los archivos con extensión .sys son esenciales para el sistema operativo.

Page 13: Operating Systems User Interfaces

DOS• El sistema de archivos que se maneja es FAT

• El sistema operativo es muy pequeño, ya casi no se utiliza y su uso ha estado limitado por el crecimiento de Windows, pero la esencia básica no ha muerto.

• La computación ha cambiado radicalmente en los últimos años que DOS ya no es funcional para las necesidades actuales de los usuarios.

Page 14: Operating Systems User Interfaces

Comandos internos• Son aquellos que se cargan en memoria por lo

que no se necesita el disco para poder ejecutarlo.

• Se encuentran en el programa command. Com o en nuevas versiones de Windows en cmd.exe

• Los comandos internos están presentes en cualquier versión de DOS aunque pueden tener diferencias como en PC-DOS, DR-DOS, FreeDOS, etc.

Page 15: Operating Systems User Interfaces

Comandos internos

• Los comandos internos proveen la funcionalidad básica del sistema.

• Los comandos externos son aquellos que se encuentran fuera del proceso command.com, necesitan del programa especificado para poder funcionar. En muchas ocasiones se les considera como utilerías.

Page 16: Operating Systems User Interfaces

Comandos internos

• Ejemplos de comandos internos son:

• DATE: cambia la fecha del sistema operativo, muy útil en sistemas antiguos que no tenían un reloj físico.

• El comando HELP muestra la ayuda del sistema, en general permite ver la sintaxis detallada y ejemplo de uso del sistema.

Page 17: Operating Systems User Interfaces

Comandos internos

• Si se escribe mal el nombre de un comando, el sistema operativo marca error indicando que no existe el archivo o comando especificado.

• Otra forma de obtener ayuda de los coamndos del sistema es a través del parámetro /?

• Los parámetros de los comandos se introducen con el carácter “/” seguido de una letra que indica la opción y opcionalmente el valor asociado.

Page 18: Operating Systems User Interfaces

Comandos internos

• TYPE: permite visualizar un archivo en pantalla.

• CHDIR: Muestra la ruta del directorio actual de trabajo.

• CLS: limpia pantalla.

• Time: permite cambiar la hora del sistema

Page 19: Operating Systems User Interfaces

Comandos internos

• VOL: muestra información sobre una unidad de almacenamiento del sistema.

• Los archivos .bat son archivos de texto que contienen instrucciones ejecutables (comandos del sistema) que pueden ejecutarse de manera no interactiva. Permiten realizar muchas actividades tediosas del sistema.

Page 20: Operating Systems User Interfaces

Comandos internos

• Otros ejemplos de comandos internos: copy, atrib, prompt, set, echo

• Ejemplos de comandos externos son: append, asign, backup, chkdsk, comp, diskcomp, discopy, fdisk, find.

Page 21: Operating Systems User Interfaces

Diferencia entre archivos y directorios

• La diferencia fundanmental entre un archivo y un directorio es en cuestión semántica. Los directorios no pueden ser procesados para almacenamiento de datos de programa sólo contienen archivos.

• En la estructura jerárquica del sistema de archivos, los directorios son todos aquellos que no se encuentran hasta el final.

Page 22: Operating Systems User Interfaces

Diferencia entre archivos y directorios

• El comando tree permite visualizar en forma jerárquica los directorios y los archivos que contiene cierta ruta.

• Aunque básicamente se realizan las mismas operaciones, los comandos son distintos para archivos como directorios.

Page 23: Operating Systems User Interfaces

Presentación de contenido de directorio

• Para visualizar el contenido de un directorio se utiliza el comando DIR

• DIR permite visualizar el contenido de diversas formas, por ejemplo el parámetro /p hace una pausa al visualizar el archivo. La opción /w los muestra en columnas. La opción /a muestra todos los archivos

Page 24: Operating Systems User Interfaces

Presentación de contenidos de un directorio

• En general los directorios aunque estén vacíos presentan dos archivos: el “.”, y el “..”, los cuales hacen referencia al directorio actual y al padre respectivamente.

• Se puede distinguir un directorio de un archivo por que los directorios tienen la palabra <dir> y los archivos muestran su tamaño en bytes al desplegar su contenido.

Page 25: Operating Systems User Interfaces

Cambio de directorio

• Para cambiar de directorio se ocupa el comando CD. El cual si es un nombre válido podemos visualizar su contenido.

• Mientras se este en un directorio, dicho directorio no puede borrase se necesita retroceder una posición actual, esto puede hacerse a través del comando cd ..

Page 26: Operating Systems User Interfaces

Creación de directorio

• El comando MD o MKDIR permite crear nuevos directorios.

• Al crear un directorio sencillamente se crea un contenedor de archivos, muchos programas utilizan directorios para organizar eficiente la información.

• Hasta que se crea un directorio, se pueden subir archivos a él.

Page 27: Operating Systems User Interfaces

Eliminación de directorio• Para borrar un directorio se utiliza la instrucción

RMDIR o RD.

• El directorio debe estar vacío de lo contrario no se podrá borrar (se pueden utilizar la opción /s para borrar todo el árbol).

• Con la combinación de teclas F3 y arriba/abajo se pueden obtener los comandos anteriores o con F1 se obtienen letra por letra el comando anterior

Page 28: Operating Systems User Interfaces

Cambio de unidades• Las unidades son el punto raíz del sistema de

archivo. Una unidad representa generalmente un dispositivo de almacenamiento como una unidad flexible (A: B:), disco duro (C:, D: y otras letras si existen particione su otros discos duros), discos ópticomos como CD, DVD (D:, E:) y otras unidades como Discos ZIP, memorias USB, etc.

• Para cambiar de directorio simplemente se pone la unidad seguido de dos puntos.

Page 29: Operating Systems User Interfaces

Manejo de rutas para archivos

• El manejo de rutas es muy importante ya que determinan la ubicación de todos los recursos de la máquina.

• Las rutas pueden ser relativas en base a donde se encuentra actualmente el usuario, o absolutas la cual indica la forma de acceder a X recurso desde cualquier parte.

• Las rutas absolutas se escriben completas, por ejemplo: c:\datos\archivo.txt

Page 30: Operating Systems User Interfaces

Uso de extensiones

• Las extensiones permiten indicarle a las aplicaciones de que archivos se trata, en la mayoría de los casos son más útiles al usuario que a el sistema operativo

• Los comandos se pueden abortar con la combinación de teclas Ctrl+C. La máquina se puede reiniciar con Ctrl+Alt+Supr

Page 31: Operating Systems User Interfaces

Uso de comodines

• Los comodines sirven para simplificar el proceso de manejo de archivos y rutas de directorio en el sistema.

• Los comodines son expresiones regulares que permiten acotar cadenas de texto

• El comodín * puede ser utilizado para sustituir de 0 a n caracteres en el nombre de un archivo.

Page 32: Operating Systems User Interfaces

Uso de comodines• El comodín ? Sustituye un carácter.

• Por ejemplo:

• DIR f*.doc, muestra todos los archivos cuyo nombre comience con f seguido de cualquier carácter.

Page 33: Operating Systems User Interfaces

Creación de archivos• Los archivos se crean a través de cualquier

aplicación. Por ejemplo, se pueden crear archivos de texto plano con la utilería edit del sistema, crear un programa en C con un compilador como Turbo C, un dibujo en CorelDraw, etc.

• Como el manejo de archivos puede ser díficil a través de comandos existen interfaces más agradables como el dosshell o el Peter Norton commander.

Page 34: Operating Systems User Interfaces

Comando format• Es un comando externo que nos permite darle

formato a una unidad o volumen.

• Dar formato consiste en preparar un disco para que acepte el sistema de archivos del sistema operativo.

• Si no se le da formato a un disco simplemente no se puede guardar la información.

Page 35: Operating Systems User Interfaces

Comando format• Una vez que un disco tiene formato ya no se

tiene que volverle a dar formato.

• Se pueden asignar diferentes capacidades de formatos así como si se quiere tener un disco de arranque del sistema con el comando sys a:

• Se puede utilizar el ratón en sistemas modo texto ocupando un controlador especial.

Page 36: Operating Systems User Interfaces

Copia de archivos

• La copia de archivos se hace a través de copy, se tiene que indicar el archivo o ruta origen y la ruta destino. Se pueden utilizar comodines para simplificar el proceso.

• Existen utilerías que simplifican el proceso de copiado como diskcopy, que copia información de un disco a otro.

Page 37: Operating Systems User Interfaces

Windows

• Windows es un sistema operativo con interfaz gráfica de usuario. Se basa en una metáfora con los escritorios de la oficina.

• Las primeras versiones eran realmente una interfaz gráfica para D.O.S.

• Trae muchas mejoras en relación con su antecesor.

Page 38: Operating Systems User Interfaces

Características

• Las primeras versiones fueron de 16 bits, actualmente es un sistema operativo de 32 bits llegando a las nuevas versiones de 64 bits.

• Es un sistema fácil de usar y aprender, multitarea, sin límites tan marcados de memoria (rompe la barrera de los 640 KB), multiusuario.

Page 39: Operating Systems User Interfaces

Características• Se ha portado a infinidad de dispositivos como

los móviles y empotrados (Windows Mobile y Windows CE)

• Es un sistema operativo modular que tiene un microkernel (kernel.exe, kernel.dll). Posee una capa de abstracción con el hardware (HAL). Tiene otros servicios como la interfaz de usuario (user.exe, user.dll), el manejo de gráficos (gdi.exe), implementa el manejo de archivos (Explorer.exe) entre otros.

Page 40: Operating Systems User Interfaces

Historia

• Microsoft anuncia "Windows“ (1983), una interface gráfica para la IBM PC, aunque fue lanzada hasta 1985. Tiene ventanas que puede superponerse y cambiar de tamaño

Page 41: Operating Systems User Interfaces

Historia

• En agosto Microsoft lanza finalmente la primera versión de Windows, aunque en esta versión las ventanas no se pueden traslapar, y las ventanas no pueden superponerse encima de la barra de menús superior.

Page 42: Operating Systems User Interfaces

Microsoft lanza la segunda versión de Windows (2.03) en 1987, la cual ya se pueden cambiar de tamaño las ventanas, sobreponer ventanas y se agregaron algunos controles nuevos sobre las ventanas.

Historia

1987

Page 43: Operating Systems User Interfaces

Microsoft lanza en mayo de 1990 Windows 3.0 al cual se le agregó un manejador de programas.

Windows 3.0

1990

Page 44: Operating Systems User Interfaces

Microsoft lanza en mayo de 1994 la primera versión de Windows NT, su sistema operativo de 32 bits. Este sistema fué nombrado como Windows 3.51 y estaba disponible para arquitecturas Intel, Power PC, Alpha y MIPS.

Windows NT

1993

Page 45: Operating Systems User Interfaces

Microsoft saca Windows 95 el 24 de agosto de 1995.

Windows 95

1995

Page 46: Operating Systems User Interfaces

Microsoft saca en 1996 Windows NT 4.0 con la misma interface que Windows 95.

Windows NT 4.0

1996

Page 47: Operating Systems User Interfaces

El 25 de junio de 1998 Microsoft saca al mercado Windows 98, el cual incluye el Internet Explorer.

Windows 98

1998

Page 48: Operating Systems User Interfaces

El 17 de febrero de 2000, Microsoft lanza Windows 2000.

Windows 2000

2000

Page 49: Operating Systems User Interfaces

El 25 de octubre de 1991 Microsoft saca al mercado Windows XP.

Windows XP

2001

Page 50: Operating Systems User Interfaces

El 24 de abril de 2003, Microsoft libera Windows Server 2003.

Windows Server 2003

2003

Page 51: Operating Systems User Interfaces

Windows Vista• Aparece el 30 noviembre de 2006. Es un

sistema con seguridad mejorada, soporte nativo a otras arquitecturas, elementos gráficos sorprendentes.

Page 52: Operating Systems User Interfaces

Windows Server 2008

Page 53: Operating Systems User Interfaces

Futuro

• Windows Seven.

• Windows CE 6.0 (Windows Mobile Photon)

• No hay nada seguro de las futuras versiones de Windows aunque probablemente saquen jugo a los procesadores de múltiples núcleo, las memorias FlashROM, la virtualización, entre otras interesantes tecnologías.

Page 54: Operating Systems User Interfaces

El escritorio• Es la parte fundamental de la interfaz, sirve de

punto de encuentro entre la computadora y el usuario.

• Todas las actividades de Windows se desarrollan sobre el escritorio. En él se encuentran las aplicaciones, archivos y demás recursos de las computadoras. A nivel de implementación es una carpeta que contiene diversos elementos (C:\Documents and settings\usuario\Escritorio)

Page 55: Operating Systems User Interfaces

El concepto de escritorio (desktop) viene de la analogía con un escritorio. Por default viene vacío, pero poco a poco se le van colocando objetos, y se pueden agregar miles de objetos y con miles de configuraciones. Algunos escritorios tienen un vidrio transparentes, en el cual se pueden colocar imágenes de fondo. Un escritorio típico tiene: Teléfono, reloj, papel, lápiz, bandeja de entrada y salida de documentos.

Escritorio Típico

Page 56: Operating Systems User Interfaces

Posteriormente se le pueden agregar marcadores, hojas para recados, papel para graficar, formatos, etc.

Herramientas

Page 57: Operating Systems User Interfaces

Con estas herramientas se puede empezar a trabajar en varios documentos a la vez

Documentos

Page 58: Operating Systems User Interfaces

En este escritorio se pueden poner revistas y mapas disponibles para que el usuario pueda consultarlos.

Accesorios

Page 59: Operating Systems User Interfaces

Si tiene suscripción a algún medio de información, como el periódico, será parte del escritorio. También se pueden agregar objetos decorativos, como un peluche, que personalizan mi área de trabajo.

Suscripciones y Personalización

Page 60: Operating Systems User Interfaces

El escritorio también puede servir como base para poder jugar en él, como por ejemplo un juego de cartas (Solitario).

Juegos

Page 61: Operating Systems User Interfaces

Temporalmente, el escritorio puede servir como un medio de almacenamiento.

Almacenamiento

Page 62: Operating Systems User Interfaces

Si se agregan accesorios, se pueden hacer copias de documentos.

Copias

Page 63: Operating Systems User Interfaces

Se agrega otro accesorio (cajón) para almacenar y ordenar información que no necesitamos en el escritorio.

Almacenar y Ordenar

Page 64: Operating Systems User Interfaces

Por último se agrega un bote de basura donde tiramos las cosas que no nos sirven, con la opción de que mientras no pase el carro de la basura, podemos extraer lo que tiramos al bote de la basura.

Bote de Basura

Page 65: Operating Systems User Interfaces

Todos los elementos anteriores nos dan como resultado la interface gráfica basada en el escritorio que conocemos hoy en día.

Escritorio

• 2005

Page 66: Operating Systems User Interfaces

Las ventanas• Es el elemento principal de la interfaz de

usuario. Son componentes en la mayoría de los casos rectangulares en los cuales se generan todas las actividades del sistema.

• Las ventanas sirven de interfaz de E/S entre los usuarios y las aplicaciones. Las ventanas comparten las mismas características. Los servicios del sistema no poseen ventanas asociadas a ellos.

Page 67: Operating Systems User Interfaces

Las ventanas

Page 68: Operating Systems User Interfaces

Los iconos y sus tipos• Son elementos visuales que representan una

acción para el usuario.

• Suelen encontrarse por toda la interfaz del sistema operativo, desde e Escritorio hasta las ventanas de aplicaciones.

• Generalmente se tiene dos tipos de íconos: los de acceso directo (asocian un ícono a una aplicación o archivo de manera rápida) y los íconos de acción.

Page 69: Operating Systems User Interfaces

Barra de tareas

• Aparecida con Windows 95, la barra de menús se ha convertido en todo un estándar en el diseño de interfaces gráficas de usuario, a tla punto que sistemas como Linux, Unix y hasta Mac OS la han imitado.

• Se encuentra generalmente en la parte inferior de la pantalla, aunque se puede encontrar en otras partes (izquierda, derecha, arriba)

Page 70: Operating Systems User Interfaces

Barra de tareas

• Dicha barra contiene las aplicaciones que se están ejecutando en ese momento por lo que la conmutación de tareas es muy rápida.

• Tambien contiene del lado izquierdo el botón inicio y del lado derecho cuenta con algunos íconos de acceso a recursos de hardware que se están monitorizando.

Page 71: Operating Systems User Interfaces

Barra de tareas

Botón de inicio Botones de aplicaciones Opciones de Teclado

Tray Reloj

Page 72: Operating Systems User Interfaces

Menú inicio

• El menú inicio permite centralizar las aplicaciones para encontrarlas de manera más fácil e intuitiva.

• Este menú se compone de accesos rápidos a las principales aplicaciones y a las aplicaciones utilizadas recientemente.

• Permite simplificar la mayoría de las tareas de manera rápida y sencilla.

Page 73: Operating Systems User Interfaces

Manejo de ventanas

6.3.1 Áreas de una ventana

6.3.2 Como mover una ventana

6.3.3 Como cambiar el tamaño de una ventana

6.3.4 Maximizar, Minimizar y restaurar

Page 74: Operating Systems User Interfaces

Áreas de una ventana• Los componentes de un ventana son:

• El área de contenido, la cual es la más grande y es en donde se realizan las diversas acciones.

• El área de título, donde se tiene el título de la aplicación, los botones de maximizar, minimizar y restaurar.

Page 75: Operating Systems User Interfaces

Áreas de una ventana• El área de menús donde se tienen las

opciones del sistema.

• El área de barra de herramientas con opciones rápidas.

• El área de la barra de estado, en donde se muestra información relevante al área de estudio.

Page 76: Operating Systems User Interfaces

Áreas de una ventana• Existen dos tipos de ventanas aquellas que

pueden tener anidadas dentro de ellas otras ventanas (MDI, Multiple Document Interface) y aquellas que sólo pueden tener una ventana anidada.

• Cuando se tienen varias ventanas, cada una de ellas puede manejar cierta funcionalidad y se pueden manipular de manera individual, aunque si se cierra la ventana padre, las hijas también se cierran.

Page 77: Operating Systems User Interfaces

Áreas de una ventana

Botón minimizar:

Envía la ventana a la barra de tareas en forma de botón liberando así espacio en el escritorio

Botón maximizar:

Aumenta de tamaño la ventana activa hasta ocupar la totalidad del escritorio

Botón cerrar:

Cierra la ventana, como en Windows cada programa es una ventana, al cerrar ésta, también se cierra la aplicación

Page 78: Operating Systems User Interfaces

Como mover una ventana• Para mover una ventana, esta no debe de estar

maximizada, si se utiliza el ratón, se debe posicionar el puntero en la barra del título y hacer drag & drop (arrastrar y soltar, se explica más adelante).

• Al mover las ventanas se redibujan. Las ventanas pueden traslaparse (modo cascada) o bien pueden organizarse de tal forma de que se puedan ver todas las ventanas en pantalla (modo mosaico).

Page 79: Operating Systems User Interfaces

Como cambiar el tamaño de una ventana

• La ventana no debe de estar maximizada para poderle cambiar el tamaño. Se posiciona el puntero del ratón sobre los bordes de la ventana (esquinas de la ventana). La forma del puntero debe cambiar a flechas dobles de tal forma que se pueda mover hacia los lados y aumentar o disminuir su tamaño.

Page 80: Operating Systems User Interfaces

Maximizar, Minimizar y restaurar

• Maximizar consiste en poner una ventana en tamaño completo, que generalmente ocupa toda el área visible de trabajo.

• Minimizar consiste en poner la ventana en modo no visible, es decir, pasa a formar parte de la barra de tareas. Al minimizar una ventana la ventana anterior pasa a formar parte del área de trabajo.

Page 81: Operating Systems User Interfaces

Maximizar, Minimizar y restaurar• Restaurar consiste en regresar una ventana a su

tamaño anterior o tamaño original. En ocasiones es una versión intermedia entre una ventana maximizada y una ventana minimizada.

• Las ventanas pueden clasificarse en activas y pasivas. Sólo existe una ventana activa y es aquella que la barra de títulos está marcada en color activo. Las ventanas activas tienen el foco de la aplicación y tienen prioridad de ejecución sobre las otras ventanas.

Page 82: Operating Systems User Interfaces

Manejo del mouse

• Windows es un sistema operativo manejado por eventos.

• Un eventos es cualquier acción que ocurre en el sistema como presionar una tecla, hacer clic con el ratón, la instalación de una aplicación, etc.

• Estos eventos son manejados por el sistema de manera transparente tanto para usuarios como para programadores.

Page 83: Operating Systems User Interfaces

Manejo del mouse

• Las interfaces gráficas de usuario requieren de mecanismos para señalizar los recursos.

• El ratón posee muchos eventos como:

• Clic, doble clic, onmove, drag and drop, entre otros.

• Las Tablet PC y algunos PDA utilizan un stylus pero mantiene el sistema los mismos eventos.

Page 84: Operating Systems User Interfaces

Manejo del mouse

• El evento OnMove, posiciona el apuntador en cierta ubicación en el escritorio.

• El evento clic se puede dar para seleccionar un elemento, ocurre cuando se presiona el boton izquierdo del mouse.

• El evento doble clic consiste en dar dos clic seguidos, se utiliza para ejecutar alguna acción

Page 85: Operating Systems User Interfaces

Manejo del mouse

• El evento Drag (arrastrar) consiste en seleccionar un elemento con un clic, dejar presionado el boton y mover el elemento alrededor de la pantalla. La variante de Drag con Drop (soltar) consiste en soltar el botón izquierdo del mouse una vez arrastrado algún elemento. Es útil en muchas actividades en Windows.

• El botón derecho del mouse generalmente se utiliza para los menús contextuales

Page 86: Operating Systems User Interfaces

Manejo del mouse

• Algunos ratones no cuentan con clic derecho pero pueden emularse con ctrl + clic izquierdo.

• Otro elemento importante consiste en el botón de scroll o botones inteligentes, que mueve la pantalla de arriba abajo.

• Todas las acciones del mouse se puedeen realizar a través del teclado.

Page 87: Operating Systems User Interfaces

Uso del teclado

• El teclado es de vital importancia en el manejo de Windows.

• Se puede manejar Windows sin ningún dispositivo señalizador sólo con el uso exclusivo de un teclado.

• Los teclados pueden diferir en el número de teclas pero generalmente se maneja una combinación de 101 teclas.

Page 88: Operating Systems User Interfaces

Uso del teclado

• El tecleado puede diferir en su conjunto de caracteres, por lo que un mismo teclado puede tener asociado varios idiomas y presentar distintos caracteres.

• Las teclas principales para el manejo de Windows son el tabulador, la teclas shift, ctrl, alt en sus diferentes combinaciones.

• Con la tecla Alt se acceden a los menús.

Page 89: Operating Systems User Interfaces

Uso del teclado

• Con la tecla shift se permiten realizar acciones sin confirmación del usuario (shift+supr) para borrar definitivamente las opciones. Tambien se utiliza para seleccionar múltiples elementos adyacentes.

• La tecla Tab permite desplazarnos de elemento gráfico por elemento. Una vez ubicado en una zona con las teclas de desplazamiento tanto izquierdas como derechas, arriba o abajo nos desplazamos por esa zona de memoria.

Page 90: Operating Systems User Interfaces

Uso del teclado

• La tecla ctrl permite seleccionar un rango no adyacente de elementos. Tambien se puede utilizar para algunos atajos de Windows

• Ctrl+Alt+Supr permite reiniciar la máquina en casi todos los sistemas operativos, en Windows permite abrir el administrador de tarea para administrar recursos como los procesos y la memoria.

Page 91: Operating Systems User Interfaces

Uso del teclado• La tecla del logotipo de Windows presente en

algunos teclados permite mostrar el menú inició de manera rápida (se puede utilizar ctrl+esc), adicionalmente se cuenta con un botón lista que abre el menú contextual.

• Alt+Esc Conmuta de tareas sin necesidad de pasar por el comnutador, Alt + Barra espaciadora abre el menú control de la ventana donde se puede maximizar, minimizar, restaurar, mover, cambiar de tamaño a una ventana entre otras.

Page 92: Operating Systems User Interfaces

Uso del teclado• Las teclas de función ya tienen asociado

cierto significado, por ejemplo F1 para la ayuda, F3 para buscar, F5 para actualizar. Esta configuración cambiará dependiendo de los programas.

• La combinación Alt+F4 cierra una ventana. Alt + Guión permite ver el menu contextual de cada ventana padre.

Page 93: Operating Systems User Interfaces

Como elegir comandos del menú

• Para elegir comandos del menú se puede utilizar el teclado o el dispositivo señalizador. Simple se selecciona una opción y si el menú tiene una opción ejecutable se realiza.

• Algunos menús se sustituyen por las barras de herramientas y en algunas ocasiones por botones de acción.

Page 94: Operating Systems User Interfaces

Como elegir comandos del menú

Page 95: Operating Systems User Interfaces

Uso del menú control

• El menú control es aquel que se encuentra situado en la parte superior izquierda.

• Este menú contiene opciones para manipular la ventana, pero también puede contener opciones personalizables, por ejemplo si se abre una terminal de DOS se puede tener acceso a la configuración de la ventana y a aspectos como copiar y pegar datos entre esas ventanas.

Page 96: Operating Systems User Interfaces

Menús contextuales

• Los menús contextuales dependen de lo que se esté utilizando. Generalmente se obtienen al hacer clic derecho.

• El menú contextual puede tener opciones de edición de un archivo, de enlaces rápidos como enviar a… y una gran variedad de aplicaciones.

Page 97: Operating Systems User Interfaces

Menús contextuales

Page 98: Operating Systems User Interfaces

Explorador de Windows

• Es el sistema que permite visualizar los archivos y recursos de la computadora se llama Explorador de Windows.

• Interactúa con el administrador de archivos para realizar todas las opciones de manipulación de recursos en Windows. Estas opciones generalmente se hacían a través de los comandos de DOS.

Page 99: Operating Systems User Interfaces

Explorador de Windows

Page 100: Operating Systems User Interfaces

Ver el contenido de unidades de disco

• Para ver el contenido de una unidad de disco se tiene que seleccionar esa unidad y abrirla.

• Se muestran generalmente todos los archivos, recordar que en Windows se manejan el concepto de unidades las cuales están siempre presente una vez conectada la unidad física. Esa unida de disco es independiente de las demás. Se manejan letras como A:, C: para hacer referencia a las unidades.

Page 101: Operating Systems User Interfaces

Copiar, mover archivos y carpetas

• Las operaciones más comunes sobre el sistema de archivos se pueden hacer de manera visual.

• Copiar es tan sencillo como seleccionar la opción correspondiente y pegar en la nueva ubicación. Si se selecciona un archivo y este se arrastra a otra carpeta generalmente se copia si están en unidades distintas, y se mueve si están en la misma unidad (para evitar este problema se puede dejar presionada la tecla ctrl o shift)

Page 102: Operating Systems User Interfaces

Copiar, mover archivos y carpetas

• Tanto los archivos como las carpetas se manejan de la misma forma, por lo que se tiene la misma semántica y no es necesario aprenderse comandos distintos.

• Para renombrar archivos se presiona la tecla F2 u opción renombrar. Generalmente las extensiones de archivos están ocultas pero pueden habilitarse a través de las opciones de carpeta del explorador. Se puede cambiar el fondo.

Page 103: Operating Systems User Interfaces

Copiar, mover archivos y carpetas

Page 104: Operating Systems User Interfaces

Inicio de aplicaciones

• Para ejecutar aplicaciones se debe de encontrar el ícono adecuado.

• Las aplicaciones que se requieran ejecutar al iniciar Windows van el menú inicio en la carpeta inicio.

• Las aplicaciones pueden ser DOS, Win16, Win32 y recientemente Win64 para micros x64.

Page 105: Operating Systems User Interfaces

Uso de mi PC• Mi PC o Equipo en Windows Vista se utiliza

como punto de encuentro de los demás procesos del sistema.

• En Mi PC se ubican generalmente las unidades y acceso directos a las principales funciones del sistema como el Panel de control, carpetas remotas, etc.

• El uso de PC facilita la utilización de Windows.

Page 106: Operating Systems User Interfaces

Uso de la papelera de reciclaje

• La papelera de reciclaje es un directorio temporal donde se guardan elementos que han sido borrados.

• Cuando se borra un archivo a través de la papelera de reciclaje, se puede recuperar este archivo, si se borró un archivo y no está en la papelera de reciclaje es muy difícil recuperarlo.

Page 107: Operating Systems User Interfaces

Panel de control

• El panel de control es la herramienta del sistema que permite configurar las opciones del sistema, contiene elementos como manejo de impresorar, instalar nuevo hardware, instalar programas, administración de periféricos y algunas opciones de software.

• El panel de control necesita tener derechos de administrador para poder funcionar.

Page 108: Operating Systems User Interfaces

Tipos de aplicaciones

• Los tipos de aplicaciones dependen de las acciones a realizar, generalmente existen aplicaciones de gestión (ofimática, nómina, contabilidad, etc.), software de ingeniería, software de sistemas, software empotrado, software de tiempo real, software para Web y software de sistemas (utilerías) entre otros.

• Las aplicaciones las debe de conocer el usuario para poderlas ejecutar.

Page 109: Operating Systems User Interfaces

Tipos de aplicaciones• Las aplicaciones tienen privilegios y opciones de

comportamiento, esas opciones son personalizables en las últimas versiones de Windows.

• Existen generalmente aplicaciones para ejecutarse sólo por el administrador o por un usuario en específico.

• Windows maneja un esquema de seguridad basado en listas de control de acceso (ACL).

Page 110: Operating Systems User Interfaces

Tipos de aplicaciones• Las ACL permiten determinar por cada usuario

que derechos se tiene sobre un recurso en particular, dichos recursos pueden ser archivos, aplicaciones, periféricos. Las versiones de servidor de Windows tienen un control más robusto sobre estas cuestiones.

• En general se tiene una lista de atributos con los derechos de acceso por usuario por cada recurso. Se tiene una configuración básica de seguridad.

Page 111: Operating Systems User Interfaces

Conmutación entre aplicaciones

• Para conmutar entre aplicaciones se puede utilizar la barra de herramientas, generalmente agrupa tareas similares en una sola entrada. Simplemente se presiona sobre la tarea que se desea tener activa. En el caso de servicios de sistemas, estos siempre se ejecutan y no es necesario conmutar entre ellos.

• Se pueden utilizar los atajos del teclado para mayor comodidad.

Page 112: Operating Systems User Interfaces

Compartir datos entre aplicaciones

• Para compartir datos se utiliza el portapapeles (Clipboard) que es un área de memoria temporal de tamaño variable que sólo puede contener un dato a la vez.

• También se pueden utilizar las Librerías de Enlace Dinámico (DLL), el registro (regedit), las variables de retorno y del sistema, entre otras muchas técnicas para compartir datos.

Page 113: Operating Systems User Interfaces

Compartir datos entre aplicaciones

• Generalmente se puede ver el contenido del portapapeles a través del visor de portapapeles. Algunos programas como office gestionan mejor el portapapeles, por lo que se pueden utilizar diversas versiones del portapapeles.

• Otra forma básica de compartir información es a través de archivos como tuberías o sockets en el caso de procesos remotos.

Page 114: Operating Systems User Interfaces

Accesorios• Los accesorios son todas aquellas aplicaciones

con las que cuenta Windows de manera predetermina y que sirven para realizar funciones básicas.

• Los accesorios tienen que ver con la metáfora del escritorio descrita al inicio de esta presentación.

• Se tiene una aplicación para escribir texto sencillo (bloc de notas), una calculadora, un programa de dibujo (paint), una agenda (lista de contacto).

Page 115: Operating Systems User Interfaces

Accesorios• Otras aplicaciones son los juegos de mesa,

un editor de texto con formato, en versiones más recientes un cliente de correo electrónico, etc.

• Se encuentran ubicadas en la carpeta accesorios del menú de inicio. Otras aplicaciones importantes son la línea de comandos, el explorador de archivos, etc.

Page 116: Operating Systems User Interfaces

Accesorios

Page 117: Operating Systems User Interfaces

Herramientas del sistema• Estas herramientas requieren de mayor

conocimiento por parte de los usuarios debido a que su uso ocupa de un conocimiento más avanzado sobre el sistema operativo.

• En algunas ocasiones cuando no se sabe algún símbolo del teclado se puede consultar el mapa de caracteres.

• Otra aplicación interesante es hyperterminal para comunicaciones remotas.

Page 118: Operating Systems User Interfaces

Herramientas del sistema

• Se cuenta con herramientas para la copias de seguridad de archivos, liberar el espacio en disco duro, restaurar sistemas, defragmentador de disco, etc.

• Existen herramientas más avanzadas como la monitorización de procesos, memoria, uso de la red, entre otros.

Page 119: Operating Systems User Interfaces

Windows• Las versiones de Windows cuentan con

clientes y en algunos casos servicios de red.

• Se pueden manejar de modo gráfico y en modo consola.

• Algunos comandos útiles son:

• Ver (muestra la versión del SO)

Page 120: Operating Systems User Interfaces

Windows• El comnado winver permite ver la versión del SO

en formato gráfico.

• Systeminfo permite ver información sobre el sistema.

• El comando help muestra ayuda sobre los comandos básicos de la consola. Se puede utilizar el parámetro /? Para conocer el funcionamiento de un comando en específico

Page 121: Operating Systems User Interfaces

Windows• Driverquery permite ver todos los controladores

cargados en el sistema

• Hostname visualiza el nombre de la maquina, también permite cambiarlo siempre y cuando se sea Administrador del Sistema.

• Openfiles permite ver archivos locales que son accedidos por clientes remotos

Page 122: Operating Systems User Interfaces

Windows• sc query (sc es un comando que permite

manipular servicios del sistema, la opción query se utiliza para mostrar los servicios activos en el sistema)

• schtask muestra información de procesos que se encuentran calendarizados en el sistema.

Page 123: Operating Systems User Interfaces

Windows• tasklist muestra todos los procesos en

ejecución.

• Taskkill permite eliminar procesos por PID o por nombre con la opción /IM

• La variable de entorno %username% tiene el nombre del usuario activo. Se puede utilizar el comando echo para imprimirlo.

Page 124: Operating Systems User Interfaces

Windows• net accounts da información sobre la máquina

actual

• Net config server (muestra información sobre el módulo del servidor del SO)

• Net config workstation (muestra información sobre el módulo del cliente)

Page 125: Operating Systems User Interfaces

Windows• Msconfig permite administrar las opciones

básicas del sistema operativo

• Mmc abre una consola administrativa para gestionar recursos

• La consola se ejecuta con el proceso cmd.exe, el comando start puede abrir diversas aplicaciones en distintas consolas.

Page 126: Operating Systems User Interfaces

Windows• Net file (sin argumentos permite observar los

archivos compartidos abiertos)

• Net localgroup, muestra los grupos de usuarios de la máquina analizada.

• Net print muestra la cola de impresión de la impresora compartida

Page 127: Operating Systems User Interfaces

Windows• Net session muestra las sesiones remotas

activas en el sistema.

• Net share muestra los recursos compartidos por el host actual. El carácter $ indica que el recurso esta oculto. Los nombres de las máquinas en Windows sigue el formato UNC: \\nombremaquina\ruta\de\acceso.

Page 128: Operating Systems User Interfaces

Windows• Net start, stop, pause y continue se utilizan para

inicializar, parar, pausar y reanudar la ejecución de un servicio de red.

• Net statistics [server|workstation] muestra información estadísticas del proceso servidor y estación de trabajo.

• Net use sin argumentos muestra las conexiones activas, con argumentos se conecta a un recurso compartido.

Page 129: Operating Systems User Interfaces

Windows• Net view muestra una lista de los equipos

conectados a la red o puede visualizar los recursos compartidos de un host remoto.

• Ipconfig permite modificar y ver los parámetros actuales de los adaptadores de red.

• Para algunos comandos se necesita ser controlador del dominio.

Page 130: Operating Systems User Interfaces

UNIX History• First developed in 1969 by Ken Thompson and Dennis Ritchie

of the Research Group at Bell Laboratories; incorporated features of other operating systems, especially MULTICS

• The third version was written in C, which was developed at Bell Labs specifically to support UNIX

• The most influential of the non-Bell Labs and non-AT&T UNIX development groups — University of California at Berkeley (Berkeley Software Distributions - BSD)– 4BSD UNIX resulted from DARPA funding to develop a

standard UNIX system for government use– Developed for the VAX, 4.3BSD is one of the most influential

versions, and has been ported to many other platforms• Several standardization projects seek to consolidate the variant

flavors of UNIX leading to one programming interface to UNIX

Page 131: Operating Systems User Interfaces

History of UNIX Versions

Page 132: Operating Systems User Interfaces

Early Advantages of UNIX

• Written in a high-level language• Distributed in source form• Provided powerful operating-

system primitives on an inexpensive platform

• Small size, modular, clean design

Page 133: Operating Systems User Interfaces

UNIX Design Principles

• Designed to be a time-sharing system• Has a simple standard user interface (shell) that

can be replaced• File system with multilevel tree-structured

directories• Files are supported by the kernel as unstructured

sequences of bytes• Supports multiple processes; a process can easily

create new processes• High priority given to making system interactive,

and providing facilities for program development

Page 134: Operating Systems User Interfaces

Programmer Interface

• Kernel: everything below the system-call interface and above the physical hardware– Provides file system, CPU scheduling,

memory management, and other OS functions through system calls

• Systems programs: use the kernel-supported system calls to provide useful functions, such as compilation and file manipulation

Like most systems, UNIX consists of two separable parts:

Page 135: Operating Systems User Interfaces

4.4BSD Layer Structure

Page 136: Operating Systems User Interfaces

System Calls• System calls define the programmer interface to

UNIX • The set of systems programs commonly available

defines the user interface• The programmer and user interface define the

context that the kernel must support• Roughly three categories of system calls in UNIX– File manipulation (same system calls also support

device manipulation)– Process control– Information manipulation

Page 137: Operating Systems User Interfaces

File Manipulation• A file is a sequence of bytes; the kernel does not impose

a structure on files• Files are organized in tree-structured directories• Directories are files that contain information on how to

find other files• Path name: identifies a file by specifying a path through

the directory structure to the file– Absolute path names start at root of file system– Relative path names start at the current directory

• System calls for basic file manipulation: create, open, read, write, close, unlink, trunc

Page 138: Operating Systems User Interfaces

Typical UNIX Directory Structure

Page 139: Operating Systems User Interfaces

Process Control• A process is a program in execution• Processes are identified by their process identifier, an integer• Process control system calls

– fork creates a new process– execve is used after a fork to replace on of the two

processes’s virtual memory space with a new program – exit terminates a process– A parent may wait for a child process to terminate; wait

provides the process id of a terminated child so that the parent can tell which child terminated

– wait3 allows the parent to collect performance statistics about the child

• A zombie process results when the parent of a defunct child process exits before the terminated child

Page 140: Operating Systems User Interfaces

Illustration of Process Control Calls

Page 141: Operating Systems User Interfaces

Process Control (Cont.)• Processes communicate via pipes; queues of

bytes between two processes that are accessed by a file descriptor

• All user processes are descendants of one original process, init

• init forks a getty process: initializes terminal line parameters and passes the user’s login name to login– login sets the numeric user identifier of the process to

that of the user– executes a shell which forks subprocesses for user

commands

Page 142: Operating Systems User Interfaces

Process Control (Cont.)

• setuid bit sets the effective user identifier of the process to the user identifier of the owner of the file, and leaves the real user identifier as it was

• setuid scheme allows certain processes to have more than ordinary privileges while still being executable by ordinary users

Page 143: Operating Systems User Interfaces

Signals• Facility for handling exceptional conditions similar

to software interrupts• The interrupt signal, SIGINT, is used to stop a

command before that command completes (usually produced by ^C)

• Signal use has expanded beyond dealing with exceptional events – Start and stop subprocesses on demand– SIGWINCH informs a process that the window in which

output is being displayed has changed size– Deliver urgent data from network connections

Page 144: Operating Systems User Interfaces

Process Groups

• Set of related processes that cooperate to accomplish a common task

• Only one process group may use a terminal device for I/O at any time– The foreground job has the attention of the user

on the terminal– Background jobs – nonattached jobs that perform

their function without user interaction• Access to the terminal is controlled by

process group signals

Page 145: Operating Systems User Interfaces

Process Groups (Cont.)

• Each job inherits a controlling terminal from its parent– If the process group of the controlling terminal

matches the group of a process, that process is in the foreground

– SIGTTIN or SIGTTOU freezes a background process that attempts to perform I/O; if the user foregrounds that process, SIGCONT indicates that the process can now perform I/O

– SIGSTOP freezes a foreground process

Page 146: Operating Systems User Interfaces

Information Manipulation• System calls to set and return an interval timer:getitmer/setitmer

• Calls to set and return the current time:gettimeofday/settimeofday

• Processes can ask for– their process identifier: getpid– their group identifier: getgid– the name of the machine on which they are

executing: gethostname

Page 147: Operating Systems User Interfaces

Library Routines

• The system-call interface to UNIX is supported and augmented by a large collection of library routines

• Header files provide the definition of complex data structures used in system calls

• Additional library support is provided for mathematical functions, network access, data conversion, etc

Page 148: Operating Systems User Interfaces

User Interface

• Programmers and users mainly deal with already existing systems programs: the needed system calls are embedded within the program and do not need to be obvious to the user

• The most common systems programs are file or directory oriented– Directory: mkdir, rmdir, cd, pwd– File: ls, cp, mv, rm• Other programs relate to editors (e.g., emacs, vi) text formatters (e.g., troff, TEX), and other activities

Page 149: Operating Systems User Interfaces

Shells and Commands• Shell – the user process which executes programs

(also called command interpreter)• Called a shell, because it surrounds the kernel• The shell indicates its readiness to accept another

command by typing a prompt, and the user types a command on a single line

• A typical command is an executable binary object file• The shell travels through the search path to find the

command file, which is then loaded and executed• The directories /bin and /usr/bin are almost

always in the search path

Page 150: Operating Systems User Interfaces

Shells and Commands (Cont.)

• Typical search path on a BSD system:

./home/prof/avi/bin /usr/local/bin /usr/ucb/bin /usr/bin

• The shell usually suspends its own execution until the command completes

Page 151: Operating Systems User Interfaces

Standard I/O

• Most processes expect three file descriptors to be open when they start:– standard input – program can read what the user types– standard output – program can send output to user’s

screen – standard error – error output• Most programs can also accept a file (rather than

a terminal) for standard input and standard output• The common shells have a simple syntax for

changing what files are open for the standard I/O streams of a process — I/O redirection

Page 152: Operating Systems User Interfaces

Standard I/O Redirection

Page 153: Operating Systems User Interfaces

Pipelines, Filters, and Shell Scripts• Can coalesce individual commands via a vertical bar that

tells the shell to pass the previous command’s output as input to the following command

% ls | pr | lpr• Filter – a command such as pr that passes its standard

input to its standard output, performing some processing on it

• Writing a new shell with a different syntax and semantics would change the user view, but not change the kernel or programmer interface

• X Window System is a widely accepted iconic interface for UNIX

Page 154: Operating Systems User Interfaces

Process Management• Representation of processes is a major design

problem for operating system• UNIX is distinct from other systems in that multiple

processes can be created and manipulated with ease

• These processes are represented in UNIX by various control blocks– Control blocks associated with a process are stored in

the kernel– Information in these control blocks is used by the kernel

for process control and CPU scheduling

Page 155: Operating Systems User Interfaces

Process Control Blocks• The most basic data structure associated with processes is the

process structure– unique process identifier– scheduling information (e.g., priority)– pointers to other control blocks

• The virtual address space of a user process is divided into text (program code), data, and stack segments

• Every process with sharable text has a pointer form its process structure to a text structure– always resident in main memory– records how many processes are using the text segment – records were the page table for the text segment can be found

on disk when it is swapped

Page 156: Operating Systems User Interfaces

System Data Segment

• Most ordinary work is done in user mode; system calls are performed in system mode

• The system and user phases of a process never execute simultaneously

• a kernel stack (rather than the user stack) is used for a process executing in system mode

• The kernel stack and the user structure together compose the system data segment for the process

Page 157: Operating Systems User Interfaces

Finding parts of a process using process structure

Page 158: Operating Systems User Interfaces

Allocating a New Process Structure

• fork allocates a new process structure for the child process, and copies the user structure– new page table is constructed– new main memory is allocated for the data

and stack segments of the child process– copying the user structure preserves open

file descriptors, user and group identifiers, signal handling, etc

Page 159: Operating Systems User Interfaces

Allocating a New Process Structure (Cont.)

• vfork does not copy the data and stack to t he new process; the new process simply shares the page table of the old one– new user structure and a new process structure are still

created– commonly used by a shell to execute a command and to wait

for its completion• A parent process uses vfork to produce a child process; the child

uses execve to change its virtual address space, so there is no need for a copy of the parent

• Using vfork with a large parent process saves CPU time, but can be dangerous since any memory change occurs in both processes until execve occurs

• execve creates no new process or user structure; rather the text and data of the process are replaced

Page 160: Operating Systems User Interfaces

CPU Scheduling• Every process has a scheduling priority associated

with it; larger numbers indicate lower priority• Negative feedback in CPU scheduling makes it

difficult for a single process to take all the CPU time• Process aging is employed to prevent starvation• When a process chooses to relinquish the CPU, it

goes to sleep on an event• When that event occurs, the system process that

knows about it calls wakeup with the address corresponding to the event, and all processes that had done a sleep on the same address are put in the ready queue to be run

Page 161: Operating Systems User Interfaces

Memory Management

• The initial memory management schemes were constrained in size by the relatively small memory resources of the PDP machines on which UNIX was developed

• Pre 3BSD system use swapping exclusively to handle memory contention among processes: If there is too much contention, processes are swapped out until enough memory is available

• Allocation of both main memory and swap space is done first-fit

Page 162: Operating Systems User Interfaces

Memory Management (Cont.)

• Sharable text segments do not need to be swapped; results in less swap traffic and reduces the amount of main memory required for multiple processes using the same text segment

• The scheduler process (or swapper) decides which processes to swap in or out, considering such factors as time idle, time in or out of main memory, size, etc

Page 163: Operating Systems User Interfaces

Paging • Berkeley UNIX systems depend primarily on paging for

memory-contention management, and depend only secondarily on swapping

• Demand paging – When a process needs a page and the page is not there, a page fault tot he kernel occurs, a frame of main memory is allocated, and the proper disk page is read into the frame

• A pagedaemon process uses a modified second-chance page-replacement algorithm to keep enough free frames to support the executing processes

• If the scheduler decides that the paging system is overloaded, processes will be swapped out whole until the overload is relieved

Page 164: Operating Systems User Interfaces

File System

• The UNIX file system supports two main objects: files and directories

• Directories are just files with a special format, so the representation of a file is the basic UNIX concept

Page 165: Operating Systems User Interfaces

Blocks and Fragments

• Most of the file system is taken up by data blocks

• 4.2BSD uses two block sized for files which have no indirect blocks:– All the blocks of a file are of a large block size

(such as 8K), except the last– The last block is an appropriate multiple of a

smaller fragment size (i.e., 1024) to fill out the file– Thus, a file of size 18,000 bytes would have two

8K blocks and one 2K fragment (which would not be filled completely)

Page 166: Operating Systems User Interfaces

Blocks and Fragments (Cont.)

• The block and fragment sizes are set during file-system creation according to the intended use of the file system:– If many small files are expected, the fragment

size should be small– If repeated transfers of large files are expected,

the basic block size should be large• The maximum block-to-fragment ratio is 8 :

1; the minimum block size is 4K (typical choices are 4096 : 512 and 8192 : 1024)

Page 167: Operating Systems User Interfaces

Inodes

• A file is represented by an inode — a record that stores information about a specific file on the disk

• The inode also contains 15 pointer to the disk blocks containing the file’s data contents– First 12 point to direct blocks– Next three point to indirect blocks

• First indirect block pointer is the address of a single indirect block — an index block containing the addresses of blocks that do contain data

• Second is a double-indirect-block pointer, the address of a block that contains the addresses of blocks that contain pointer to the actual data blocks.

• A triple indirect pointer is not needed; files with as many as 232 bytes will use only double indirection

Page 168: Operating Systems User Interfaces

Directories• The inode type field distinguishes between plain

files and directories• Directory entries are of variable length; each entry

contains first the length of the entry, then the file name and the inode number

• The user refers to a file by a path name,whereas the file system uses the inode as its definition of a file– The kernel has to map the supplied user path name to

an inode– Directories are used for this mapping

Page 169: Operating Systems User Interfaces

Directories (Cont.)• First determine the starting directory:– If the first character is “/”, the starting directory is the root

directory– For any other starting character, the starting directory is the

current directory• The search process continues until the end of the path

name is reached and the desired inode is returned• Once the inode is found, a file structure is allocated to

point to the inode• 4.3BSD improved file system performance by adding a

directory name cache to hold recent directory-to-inode translations

Page 170: Operating Systems User Interfaces

Mapping of a File Descriptor to an Inode

• System calls that refer to open files indicate the file is passing a file descriptor as an argument

• The file descriptor is used by the kernel to index a table of open files for the current process

• Each entry of the table contains a pointer to a file structure

• This file structure in turn points to the inode• Since the open file table has a fixed length which

is only setable at boot time, there is a fixed limit on the number of concurrently open files in a system

Page 171: Operating Systems User Interfaces

File-System Control Blocks

Page 172: Operating Systems User Interfaces

Disk Structures

• The one file system that a user ordinarily sees may actually consist of several physical file systems, each on a different device

• Partitioning a physical device into multiple file systems has several benefits– Different file systems can support different uses– Reliability is improved– Can improve efficiency by varying file-system parameters– Prevents one program form using all available space for a

large file– Speeds up searches on backup tapes and restoring

partitions from tape

Page 173: Operating Systems User Interfaces

Disk Structures (Cont.)

• The root file system is always available on a drive

• Other file systems may be mounted — i.e., integrated into the directory hierarchy of the root file system

• The following figure illustrates how a directory structure is partitioned into file systems, which are mapped onto logical devices, which are partitions of physical devices

Page 174: Operating Systems User Interfaces

Mapping File System to Physical Devices

Page 175: Operating Systems User Interfaces

Implementations• The user interface to the file system is simple and well defined,

allowing the implementation of the file system itself to be changed without significant effect on the user

• For Version 7, the size of inodes doubled, the maximum file and file system sized increased, and the details of free-list handling and superblock information changed

• In 4.0BSD, the size of blocks used in the file system was increased form 512 bytes to 1024 bytes — increased internal fragmentation, but doubled throughput

• 4.2BSD added the Berkeley Fast File System, which increased speed, and included new features

– New directory system calls– truncate calls– Fast File System found in most implementations of UNIX

Page 176: Operating Systems User Interfaces

Layout and Allocation Policy

• The kernel uses a <logical device number, inode number> pair to identify a file– The logical device number defines the file system

involved– The inodes in the file system are numbered in sequence

• 4.3BSD introduced the cylinder group — allows localization of the blocks in a file– Each cylinder group occupies one or more consecutive

cylinders of the disk, so that disk accesses within the cylinder group require minimal disk head movement

– Every cylinder group has a superblock, a cylinder block, an array of inodes, and some data blocks

Page 177: Operating Systems User Interfaces

4.3BSD Cylinder Group

Page 178: Operating Systems User Interfaces

I/O System

• The I/O system hides the peculiarities of I/O devices from the bulk of the kernel

• Consists of a buffer caching system, general device driver code, and drivers for specific hardware devices

• Only the device driver knows the peculiarities of a specific device

Page 179: Operating Systems User Interfaces

4.3 BSD Kernel I/O Structure

Page 180: Operating Systems User Interfaces

Block Buffer Cache

• Consist of buffer headers, each of which can point to a piece of physical memory, as well as to a device number and a block number on the device

• The buffer headers for blocks not currently in use are kept in several linked lists: – Buffers recently used, linked in LRU order (LRU list)– Buffers not recently used, or without valid contents (AGE list)– EMPTY buffers with no associated physical memory

• When a block is wanted from a device, the cache is searched• If the block is found it is used, and no I/O transfer is necessary• If it is not found, a buffer is chosen from the AGE list, or the LRU

list if AGE is empty

Page 181: Operating Systems User Interfaces

Block Buffer Cache (Cont.)

• Buffer cache size effects system performance; if it is large enough, the percentage of cache hits can be high and the number of actual I/O transfers low

• Data written to a disk file are buffered in the cache, and the disk driver sorts its output queue according to disk address — these actions allow the disk driver to minimize disk head seeks and to write data at times optimized for disk rotation

Page 182: Operating Systems User Interfaces

Raw Device Interfaces

• Almost every block device has a character interface, or raw device interface — unlike the block interface, it bypasses the block buffer cache

• Each disk driver maintains a queue of pending transfers• Each record in the queue specifies:

– whether it is a read or a write – a main memory address for the transfer– a device address for the transfer– a transfer size

• It is simple to map the information from a block buffer to what is required for this queue

Page 183: Operating Systems User Interfaces

C-Lists

• Terminal drivers use a character buffering system which involves keeping small blocks of characters in linked lists

• A write system call to a terminal enqueues characters on a list for the device. An initial transfer is started, and interrupts cause dequeueing of characters and further transfers

• Input is similarly interrupt driven• It is also possible to have the device driver bypass the

canonical queue and return characters directly form the raw queue — raw mode (used by full-screen editors and other programs that need to react to every keystroke)

Page 184: Operating Systems User Interfaces

Interprocess Communication

• The pipe is the IPC mechanism most characteristic of UNIX– Permits a reliable unidirectional byte stream between two

processes– A benefit of pipes small size is that pipe data are seldom

written to disk; they usually are kept in memory by the normal block buffer cache

• In 4.3BSD, pipes are implemented as a special case of the socket mechanism which provides a general interface not only to facilities such as pipes, which are local to one machine, but also to networking facilities

• The socket mechanism can be used by unrelated processes

Page 185: Operating Systems User Interfaces

Sockets

• A socket is an endpont of communication• An in-use socket it usually bound with an address; the

nature of the address depends on the communication domain of the socket

• A characteristic property of a domain is that processes communication in the same domain use the same address format

• A single socket can communicate in only one domain — the three domains currently implemented in 4.3BSD are:– the UNIX domain (AF_UNIX)– the Internet domain (AF_INET)– the XEROX Network Service (NS) domain (AF_NS)

Page 186: Operating Systems User Interfaces

Socket Types• Stream sockets provide reliable, duplex, sequenced data streams.

Supported in Internet domain by the TCP protocol. In UNIX domain, pipes are implemented as a pair of communicating stream sockets

• Sequenced packet sockets provide similar data streams, except that record boundaries are provided– Used in XEROX AF_NS protocol

• Datagram sockets transfer messages of variable size in either direction. Supported in Internet domain by UDP protocol

• Reliably delivered message sockets transfer messages that are guaranteed to arrive (Currently unsupported)

• Raw sockets allow direct access by processes to the protocols that support the other socket types; e.g., in the Internet domain, it is possible to reach TCP, IP beneath that, or a deeper Ethernet protocol– Useful for developing new protocols

Page 187: Operating Systems User Interfaces

Socket System Calls

• The socket call creates a socket; takes as arguments specifications of the communication domain, socket type, and protocol to be used and returns a small integer called a socket descriptor

• A name is bound to a socket by the bind system call• The connect system call is used to initiate a connection• A server process uses socket to create a socket and bind to

bind the well-known address of its service to that socket– Uses listen to tell the kernel that it is ready to accept

connections from clients– Uses accept to accept individual connections– Uses fork to produce a new process after the accept to

service the client while the original server process continues to listen for more connections

Page 188: Operating Systems User Interfaces

Socket System Calls (Cont.)

• The simplest way to terminate a connection and to destroy the associated socket is to use the close system call on its socket descriptor

• The select system call can be used to multiplex data transfers on several file descriptors and /or socket descriptors

Page 189: Operating Systems User Interfaces

Network Support• Networking support is one of the most important features in

4.3BSD• The socket concept provides the programming mechanism to

access other processes, even across a network• Sockets provide an interface to several sets of protocols• Almost all current UNIX systems support UUCP• 4.3BSD supports the DARPA Internet protocols UDP, TCP, IP,

and ICMP on a wide range of Ethernet, token-ring, and ARPANET interfaces

• The 4.3BSD networking implementation, and to a certain extent the socket facility, is more oriented toward the ARPANET Reference Model (ARM)

Page 190: Operating Systems User Interfaces

Network Reference models and Layering

Page 191: Operating Systems User Interfaces

191

The History of Linux

• The real history of Linux starts in 1969, when Ken Thompson developed the first version of UNIX at Bell Labs – After Dennis Ritchie, designer of the C programming language,

joined the project it debuted to the research community in an academic paper in 1974

– Bell Labs released the first commercial version in 1976 as UNIX Version 6 (V6)

• UNIX spread throughout universities and in 1978 Bell Labs released UNIX Time-Sharing System, a version with portability in mind

Page 192: Operating Systems User Interfaces

192

Linux History Continued

• Because Bell Labs distributed UNIX with source code, the early 1980’s saw three major branches grow on the UNIX tree:– UNIX System III from Bell Lab’s UNIX Support Group (USG)– UNIX Berkeley Source Distribution (BSD) from the University of

California at Berkeley– Microsoft’s XENIX

• The UNIX market fragmented further in the 1980’s, despite the IEEE’s POSIX standard and the X/Open Group’s Portability Guide

Page 193: Operating Systems User Interfaces

193

Linus and Linux

• In 1991 Linus Torvalds took a college computer science course that used the Minix operating system– Minix is a “toy” UNIX-like OS written by Andrew Tanenbaum as a

learning workbench– Linus wanted to make MINIX more usable, but Tanenbaum

wanted to keep it ultra-simple• Linus went in his own direction and began working on

Linux– In October 1991 he announced Linux v0.02– In March 1994 he released Linux v1.0

Page 194: Operating Systems User Interfaces

194

The History of Windows (NT)• The history of Windows really begins in the mid-1970s,

when Dick Hustvedt, Peter Lipman and David Cutler designed the VMS operating system for Digital’s 32-bit VAX processor– Digital shipped VMS v1.0 in 1978

• Cutler moved to Seattle to open DECWest and worked on the Digital Mica OS for a new CPU codenamed Prism– 12 engineers went with him and the facility grew to 200– In 1988 Digital cancelled the project

Page 195: Operating Systems User Interfaces

195

The History of Windows Continued

• Bill Gates wanted a UNIX rival– He hired Cutler and 20 Digital engineers in 1989– The new project was called NT OS/2 because it focused on OS/2

backward compatibility

• With the success of Windows 3.0’s 1990 release Gates refocused the project on Windows compatibility– The project renamed to Windows NT– Microsoft released Windows NT 3.1 in August 1993

Page 196: Operating Systems User Interfaces

196

Windows and Linux

• Both Linux and Windows are based on foundations developed in the mid-1970s1970 1980 1990 2000

UNIX bo

rnUNIX

publi

cUNIX

V6

Linux

v1.0

v2.0

v2.1

v2.2

v2.3

v2.4

v2.6

1970 1980 1990 2000

VMS v1.0

Wind

ows N

T 3.1

NT 4.

0W

indow

s 200

0W

indow

s XP

Server

2003

Page 197: Operating Systems User Interfaces

[Linux@panorama]# • Linus Torvalds, estudiante de la Universidad de

Helsinki, creó Linux por hobby. Él estaba interesado en Minix, un sistema UNIX pequeño, y decidió desarrollar un sistema operativo que excediera los estándares de Minix. Comenzó su trabajo en 1991 con la versión 0.02 y continuó hasta que en 1994 liberó el kernel de Linux, versión 1.0

Page 198: Operating Systems User Interfaces

[Linux@panorama]#• Los desarrollos continúan a cargo de

numerosas organizaciones y programadores independientes, porque Torvalds registro a Linux bajo Licencia Pública General (GNU). cualquier persona puede usar, modificar y distribuir Linux, pero no restringir su posterior distribución. El desarrollador está obligado a poner a disposición de los demás el código fuente.

Page 199: Operating Systems User Interfaces

[LINUX@panorama]#• Linux introdujo los conceptos de velocidad,

eficiencia y flexibilidad de UNIX, a las microcomputadoras.

• Primera versión comercial distribuida en marzo de 1994 (kernel 1.0)

• Linux no es un UNIX.• Linux mejoró notablemente las “curses” de

Unix.

Page 200: Operating Systems User Interfaces

[UNIX@panorama]#• Deriva de un SO llamado MULTICS

(Multiplexed Information & Computing System).• Desarrollado en los laboratorios Bell, por

Kernigham en 1973.• Un SO de programadores para programadores.• La columna vertebral del Internet.

Page 201: Operating Systems User Interfaces

[Características@panorama]#• Multitarea real• Conectividad TCP/IP• Manejo de memoria virtual usando paginación• Librerías compartidas• Multiusuario• Manejo uniforme de recursos de E/S

Page 202: Operating Systems User Interfaces

[Características@panorama]#• Tiempo Real• Multiplataforma• Protección de memoria entre procesos• Se realizan volcados de estado• Todo el código fuente está disponible.• Consolas virtuales múltiples• Soporte para varios sistemas de archivos• Sistema de cuotas para los recursos• Construcción de sistemas ciegos

Page 203: Operating Systems User Interfaces

[Características@panorama]#• Se basa en las especificaciones de

POSIX del IEEE:–Uniformidad– Aplicaciones pueden pasar de Linux a

System V y al BSD.– Soporte de funciones de UNIX.

Page 204: Operating Systems User Interfaces

[Características@panorama]#• Linux fue creado en base a la filosofía muchos

usuarios, una computadora.

• Windows fue creado bajo el paradigma un usuario, una computadora en cada escritorio y hogar.

• Windows integra la GUI en el Kernel. Linux no, por eso es más estable.

Page 205: Operating Systems User Interfaces

[Hardware@panorama]#• ARM • Intel X86• NeXT• Amiga• Motorola 68x00• MIPS • Alpha• Silicon Graphics, etc.

Page 206: Operating Systems User Interfaces

[Embedded@panorama]#

Page 207: Operating Systems User Interfaces

[uso@panorama]#

Page 208: Operating Systems User Interfaces

[¿Gratis?@panorama]#Gratis != Libre

Algunas excepciones:

• Caldera DR-DOS• Oracle para Linux• Red Hat, Mandrake• Informix-SE para Linux

Page 209: Operating Systems User Interfaces

[Desventajas@panorama]#• No existen todos los controladores para

algunos periféricos como el escáner en paralelo, o el reproductor de DVD.

• Los controladores no soportan bien cualquier dispositivo.

• Se necesita mayor capacitación

Page 210: Operating Systems User Interfaces

[Desventajas@panorama]#

• No hay versiones estandarizadas.• Comandos demasiado breves.

Comando MS-DOS UNIX VMS

Listar archivos Dir ls DIRECTORY

Cambiar de directorio CD o CHDIR cd SET DEFAULT

Copiar archivo COPY cp COPY

Renombrar un archivo RENAME mv RENAME

Page 211: Operating Systems User Interfaces

[FUD@panorama]• Fear, Uncertainty, Doubt; es una técnica de mercadeo

cuando un competidor lanza un producto nuevo que es mucho mejor y que reduce costos.

• Linux es inseguro• No existe personal capacitado• No es compatible con Windows• Es muy difícil

Page 212: Operating Systems User Interfaces

[Preocupaciones por usar Windows@panorama]#• 80% Calidad del software o vulnerabilidad

• 64% Costo de propiedad muy alto• 55% Monopolio de Microsoft• 31% Manejo de problemas cuando surgen• 31% Mejores herramientas de administración• 28% Escalabilidad• 17% Falta de un completo e integrado ambiente de cómputo• 17% Falta de un mapa claro de desarrollo del producto• 16% Aspectos de licenciamiento• 5% Otros• 9% Ninguno

Page 213: Operating Systems User Interfaces

[Razones para usar Linux@panorama]#

• 90% Costo de licenciamiento gratuito o muy bajo

• 88% Confiabilidad• 81% Desempeño• 70% Necesita alternativa a Windows• 48% Herramientas de desarrollo disponibles en

Internet

Page 214: Operating Systems User Interfaces

[Razones para no utilizar Linux@panorama]#• 61% Aplicaciones Clave del negocio no corren en Linux

• 49% Personal de TI no está entrenado en Linux• 42% Proveedores independientes de Software no lo respaldan• 41% Prefieren otro sistema operativo• 34% Preocupación por desempeño• 31% No quiere manejar múltiples sistemas operativos• 30% No confía en software open-source• 22% Preocupación por escalabilidad• 18% Proveedores de equipos no lo respaldan• 16% Otras razones

Page 215: Operating Systems User Interfaces

[Razones para usar Windows@panorama]#• 70% Adecuada integración con otros productos de Microsoft

• 68% Amplia disponibilidad de software aplicativo• 27% Buen desempeño y disponibilidad• 24% Buenas herramientas administrativas• 23% Buen servicio y soporte• 20% Expectativa en innovación futura• 19% Confianza en el modelo económico de Microsoft• 18% Bajo costo• 17% Buena integración con plataformas no Microsoft• 10% Ambiente seguro• 14% Otros

Page 216: Operating Systems User Interfaces

[Razones de empresas para seleccionar Linux@panorama]#• 60% Bajo costo

• 50% Buen desempeño y disponibilidad• 41% Ambiente seguro• 40% Expectativa por innovación futura• 39% Confianza en el modelo open source• 21% Buenas herramientas de administración• 12% Buena integración con otro software de servidor• 12% Alta disponibidlidad de software aplicativo• 11% Soporte y servicio• 4% Otra

Page 217: Operating Systems User Interfaces

[Temores para usar Linux@panorama]#• 40% Falta de un ambiente completo e integrado de cómputo

• 37% Falta de responsable si salen problemas• 35% Falta de un mapa claro de desarrollo de producto• 27% Posibles problemas de propiedad intelectual• 27% Mejores herramientas administrativas• 23% Calidad del software y vulnerabilidades• 7% Escalabilidad• 2% Alto costo de propiedad• 4% Otro• 27% No tiene preocupaciones

Page 218: Operating Systems User Interfaces

[Usos comunes para Linux@panorama]#• 80% Servidores Web o Intranet

• 60% Administración Bases de Datos• 58% Correo Electrónico o mensajería• 57% Desarrollo de Aplicaciones• 54% PC's de Escritorio• 50% Servidor de Archivos e impresoras• 40% Administración de sistemas• 32% Aplicaciones Corporativas• 21% Servidores comercio electrónico• 10% Servidores delgados y “cuchichas”• 6% Clusters de supercomputadores• 24% Otros usos

Page 219: Operating Systems User Interfaces

[Requisitos@panorama]#ESTACIÓN

DE TRABAJO

SERVIDOR

PROCESADOR Desde 386 Pentium a 133

MEMORIA Desde 8 MB 32 MB (como mínimo)

DISCO DURO Desde 300 MB

Desde 600 MB

Page 220: Operating Systems User Interfaces

[Mapa@panorama]#

Page 221: Operating Systems User Interfaces

[Sabores@panorama]#• ¿Qué refresco de cola es mejor?

• Coca• Pepsi• Gallito• Bigcola• …

Page 222: Operating Systems User Interfaces

[Sabores@panorama]#• Caldera Open-Linux, Debian GNU/Linux, DLX

Linux, DOS Linux, hal91, LinuxPPC, Linux Pro, Linux Ware, MkLinux, RedHat Linux, Slackware Linux, StempedeLinux, S.u.S.E, Linux, TurboLinux, Yggdrasil Linux, Dexil DLD Linux, Eagle Linux, Eurielec Linux, Kheops Linux, MNIS Linux.

Page 223: Operating Systems User Interfaces

[Variantes@panorama]#• IRIX• AIX• FreeBSD• Unix System V• HPUX• Solaris• Ultrix

• Unix BSD• FreeBSD• OpenBSD• NetBSD

Page 224: Operating Systems User Interfaces

[Gartner 2007@panorama]#1. Código abierto2. Virtualización 3. Registro de servicios y repositorios4. Suites para la gestión de procesos de negocios5. Enterprise Information Management6. Cómputo ubicuo7. Acceso a la información 8. Web 2.0 – AJAX Rich Clients 9. Web 2.0 - Mashup Composite Model10. Inteligencia colectiva y comunidades

Page 225: Operating Systems User Interfaces

[IDC 2007@panorama]#1. Virtualización2. Grid Computing3. Arquitectura orientada a servicios (SOA)4. Enterprise Information Management (EIM)5. Código abierto6. Acceso a la información7. Ajax8. Mashup Composite Model9. Computación Distribuida en el Ambiente (Pervasive

Computing)10. Recolección inteligente de datos

Page 226: Operating Systems User Interfaces

[GPL@panorama]#• GNU Public License, se puede vender el

software pero con código libre. Otras licencias: Copyleft y Creative Commons.

• Desde la versión 2.2.0 la contibución de Linus es menos del 5% del total

• “El dinero no está en el producto, sino en los servicios que están con él” IBM

Page 227: Operating Systems User Interfaces

[Catedral y el bazar@panorama]#• Eric Random• Fecthmail• Cathedral Comercial• Bazar Linux

• “Dado un número suficiente de ojos, todos los errores son irrelevantes”.

Page 228: Operating Systems User Interfaces

[Bazar@panorama]#• Todo buen trabajo de software comienza

rasguñando una inquietud personal del desarrollador.

• Los buenos programadores saben que escribir. Los grandes saben que re-escribir (y reusar).

• Cuando se pierde interés en un programa, el último deber es ponerlo en manos de un sucesor competente.

Page 229: Operating Systems User Interfaces

[Bazar@panorama]#• Tratar a tus usuarios como colaboradores es

el camino menos complicado para mejorar con rapidez, y depurar eficazmente un programa.

• Libera pronto. Libera frecuentemente. Y escucha a tus usuarios.

Page 230: Operating Systems User Interfaces

[Bazar@panorama]#• Dada una base lo suficientemente grande de

probadores y colaboradores, casi cualquier problema se identificará con rapidez y el arreglo será obvio para alguien.

• Estructuras de datos inteligentes asociadas a un código torpe funcionan mucho mejor que la alternativa opuesta.

Page 231: Operating Systems User Interfaces

[Bazar@panorama]#• “Enséñame tu código y mantén ocultas tus

estructuras de datos, y me seguirás engañando. Muéstrame tus estructuras de datos y normalmente no necesitaré que me enseñes tu código: resultará evidente”.

• Si se tratan a la gente que te ayuda a depurar como si fueran el recurso más valioso, responderán convirtiéndose en eso precisamente.

Page 232: Operating Systems User Interfaces

[Bazar@panorama]#• Algo mejor que tener buenas ideas es

reconocer las buenas ideas de los usuarios. Y en ocasiones esta última es la mejor en términos absolutos.

• Con frecuencia, las soluciones más impactantes e innovadoras vienen de darse cuenta que el concepto del problema está equivocado.

Page 233: Operating Systems User Interfaces

[Bazar@panorama]#• Antoine de Saint-Exupory dijo: “La perfección

(en diseño) no se obtiene cuando no hay nada mas que agregar, sino cuando no hay nada mas que desechar..”

• Epílogo de Netscape: es extraño sentir que realizas algo para hacer historia.

Page 234: Operating Systems User Interfaces

[Instalación@Unidad I]$• Realizar respaldo de archivos y

configuraciones.

• Si se desea tener un sistema de arranque múltiple instalar primero los sistemas operativos y hasta el final Linux.

• Realizar particionado de preferencia manual antes de la instalación

Page 235: Operating Systems User Interfaces

[Instalación@Unidad I]$• Se deberá elegir el tipo de instalación: modo

gráfico, modo texto o modo experto.

• Se deberá tener conocimiento sobre el hardware del equipo.

• Se deberá saber que uso se le dará a la máquina para así seleccionar el tipo de instalación y conocer los paquetes a instalar.

Page 236: Operating Systems User Interfaces

[Instalación@Unidad I]$• La mayoría de las distribuciones de Linux cuentan con

instaladores para:– Clientes – Estaciones de Trabajo– Servidores

• Se recomienda en servidor no instalar interfaz gráfica y paquetes que no se usan

• El problema no es instalar Linux sino configurarlo

Page 237: Operating Systems User Interfaces

[Cliente/Servidor@Unidad I]$

Cliente

Servidor

Petición

Respuesta

Page 238: Operating Systems User Interfaces

[Computadoras@Unidad I]$• El término cliente/servidor se refiere a procesos

pero se asocia con máquinas

• Supercomputadoras• Mainframes (macrocomputadoras)• Estaciones de trabajos (minicomputadoras)• Computadoras personales

(microcomputadoras).

Page 239: Operating Systems User Interfaces

[Cliente/Servidor@Unidad I]$• Servidor: a computadoras de gran tamaño,

brindan servicios a otras máquinas.

• Cliente: computadoras de menor tamaño, limitadas en recursos, reciben servicios de los servidores. Terminales tontas.

• Estaciones de trabajo: computadoras de mayores prestaciones que los clientes pero menores que los servidores.

Page 240: Operating Systems User Interfaces

[Actualización@Unidad I]$• La actualización es más lenta. Es mejor realizar

un respaldo y luego instalar.

• Particiones: /, /usr, /var, /home, /tmp, /boot y Swap.

• Disk druid es un asistente para particionado.• NTFS es más estricto a la hora de realizar

modificaciones en las particiones.

Page 241: Operating Systems User Interfaces

[Instalación de paquetes@Unidad I]$• tar –xzvf paquete.tar.gz• cd paquete

• ./configure

• make

• make install

Page 242: Operating Systems User Interfaces

[Instalación de sw@Unidad I]$• rpm –i paquete• rpm –U actualiza paquete

• rpm –qa• rpm -qi• rpm –qf

• rpm –e desinstala paquete

Page 243: Operating Systems User Interfaces

[Configuración SW@Unidad I]$• Linux no cuenta con un registro pero si con

archivos de configuración. Las primeras versiones de Windows no tenían Registro (archivos .INI)

• La configuración depende de cada servicio.

• La localización de los archivos de configuración puede variar en cada distribución

Page 244: Operating Systems User Interfaces

[apt@Unidad I]$• Advanced Packaging Tool.

• /etc/apt/sources.list• apt-get install paquete• apt-get remove paquete• apt-get –reinstall install paquete• apt-cdrom ruta add• apt-get -u install lilo

Page 245: Operating Systems User Interfaces

[GUI@Unidad I]$• XFree86

• Enlightenment• WindowMaker• Blackbox• FluxBox

• GNOME• KDE

Page 246: Operating Systems User Interfaces

[GUI@Unidad I]$• Startx• .xinitrc

• #!/bin/sh• gnome-sesion

Page 247: Operating Systems User Interfaces

[KDE@Unidad I]$• KDE (K Desktop Environment) es un entorno de

escritorio gráfico e infraestructura de desarrollo para sistemas Unix y, en particular, Linux.

• KDE imitó a CDE (Common Desktop Environment) en sus inicios. CDE es un entorno de escritorio utilizado por varios Unix.

• De acuerdo con su página Web, "KDE es un entorno gráfico contemporáneo para estaciones de trabajo Unix. KDE llena la necesidad de un escritorio amigable para estaciones de trabajo Unix, similar a los escritorios de MacOS o Windows".

Page 248: Operating Systems User Interfaces

[GNOME@Unidad I]$• GNOME o Gnome es un entorno de escritorio

para sistemas operativos de tipo Unix bajo tecnología X Window, se encuentra disponible actualmente en más de 35 idiomas. Forma parte oficial del proyecto GNU.

• Creado por el mexicano Miguel de Icaza.

Page 249: Operating Systems User Interfaces

[Ofimática@Unidad I]$• Ofimática: Suite con Procesador de texto, hojas

electrónicas, presentaciónes, gráficas y bases de datos.

• StarOffice 6.0, Sun Microsystems Inc.(Windows, Linux, Solaris)

• OpenOffice.org (Windows, Linux, Solaris)

• Koffice

Page 250: Operating Systems User Interfaces

[Navegadores@Unidad I]$• Netscape (www.netscape.com) • Mozilla (www.mozilla.org)• FireFox (www.firefox.com)

• Opera (www.opera.com)• Konqueror (KDE) (www.kde.org)

• Lynx

Page 251: Operating Systems User Interfaces

[Antivirus@Unidad I]$• OpenAntiVirus Project www.openantivirus.org

• CLAM Antivirus http://clamav.elektrapro.com

• AMaViS – A Mail Virus Scanner www.amavis.org

• Sophos – www.sophos.com

Page 252: Operating Systems User Interfaces

[mtools@Unidad I]$• Comandos de MS-DOS• mcopy

• /etc/mtools.conf. • drive a: file="/dev/fd0" exclusive drive b:

file="/dev/fd1" exclusive # 1er disco Duro drive c: file="/dev/hda1" # 2nd disco Duro drive d: file="/dev/sda1" mtools_lower_case=1

Page 253: Operating Systems User Interfaces

[Emuladores@Unidad I]$• DOSemu para MS-DOS• Wine para Windows

• Virtualización:– VMware– Zen– Bosch

Page 254: Operating Systems User Interfaces

[Otras apliacaciones@Unidad I]$• Existen muchas aplicaciones de software libre

y propietario para Linux que abarcan prácticamente todas las áreas del quehacer humano.

• La ventaja del software libre es que muchas de las versiones de programas para Linux existen también para otros SOs.

Page 255: Operating Systems User Interfaces

[Lenguajes@]$• C Compilador gcc• C++ Compilador g++• GNU Fortran 77

• Tcl– Button .b –text “Hola mundo!” –comand exit– Pack .b

Page 256: Operating Systems User Interfaces

[Lenguajes@Unidad I]$• Perl

• Python

• Ruby

• AWK

Page 257: Operating Systems User Interfaces

[Servidor Stream]@Unidad I]$#include <stdio.h>

#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <sys/wait.h>#include <signal.h>

#define MYPORT 3490 // Puerto al que conectarán los usuarios

#define BACKLOG 10 // Cuántas conexiones pendientes se mantienen en cola

void sigchld_handler(int s){while(wait(NULL) > 0);}

int main(void){int sockfd, new_fd; // Escuchar sobre sock_fd, nuevas conexiones sobre new_fdstruct sockaddr_in my_addr; // información sobre mi direcciónstruct sockaddr_in their_addr; // información sobre la dirección del clienteint sin_size;struct sigaction sa;int yes=1;

Page 258: Operating Systems User Interfaces

[Servidor Stream]@Unidad I]$if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {perror("socket");exit(1);}

if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {perror("setsockopt");exit(1);}

my_addr.sin_family = AF_INET; // Ordenación de bytes de la máquinamy_addr.sin_port = htons(MYPORT); // short, Ordenación de bytes de la redmy_addr.sin_addr.s_addr = INADDR_ANY; // Rellenar con mi dirección IPmemset(&(my_addr.sin_zero), '\0', 8); // Poner a cero el resto de la estructura

}

Page 259: Operating Systems User Interfaces

[Servidor Stream]@Unidad I]$if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1) {perror("bind");exit(1);}

if (listen(sockfd, BACKLOG) == -1) {perror("listen");exit(1);}

sa.sa_handler = sigchld_handler; // Eliminar procesos muertossigemptyset(&sa.sa_mask);sa.sa_flags = SA_RESTART;if (sigaction(SIGCHLD, &sa, NULL) == -1) {perror("sigaction");exit(1);}

return 0;

Page 260: Operating Systems User Interfaces

[Servidor Stream]@Unidad I]$while(1) { // main accept() loopsin_size = sizeof(struct sockaddr_in);if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size)) == -1) {perror("accept");continue;}printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));if (!fork()) { // Este es el proceso hijoclose(sockfd); // El hijo no necesita este descriptorif (send(new_fd, "Hello, world!\n", 14, 0) == -1)perror("send");close(new_fd);exit(0);}close(new_fd); // El proceso padre no lo necesita}

Page 261: Operating Systems User Interfaces

[Cliente Stream@Unidad I]$• #include <stdio.h>

#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <netdb.h>#include <sys/types.h>#include <netinet/in.h>#include <sys/socket.h>

#define PORT 3490 // puerto al que vamos a conectar

#define MAXDATASIZE 100 // máximo número de bytes que se pueden leer de una vez

int main(int argc, char *argv[]){int sockfd, numbytes; char buf[MAXDATASIZE];struct hostent *he;struct sockaddr_in their_addr; // información de la dirección de destino

memset(&(their_addr.sin_zero), 8); // poner a cero el resto de la estructura

Page 262: Operating Systems User Interfaces

[Cliente Stream@Unidad I]$if (argc != 2) {fprintf(stderr,"usage: client hostname\n");exit(1);}

if ((he=gethostbyname(argv[1])) == NULL) { // obtener información de máquina perror("gethostbyname");exit(1);}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {perror("socket");exit(1);}

their_addr.sin_family = AF_INET; // Ordenación de bytes de la máquina their_addr.sin_port = htons(PORT); // short, Ordenación de bytes de la red their_addr.sin_addr = *((struct in_addr *)he->h_addr);

Page 263: Operating Systems User Interfaces

[Cliente Stream@Unidad I]$if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct sockaddr)) == -1) {perror("connect");exit(1);}

if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {perror("recv");exit(1);}

buf[numbytes] = '\0';

printf("Received: %s",buf);

close(sockfd);

return 0;}

Page 264: Operating Systems User Interfaces

[Servidor Datagrama@Unidad I]$#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>

#define MYPORT 4950 // puerto al que conectarán los clientes

#define MAXBUFLEN 100

int main(void){int sockfd;struct sockaddr_in my_addr; // información sobre mi direcciónstruct sockaddr_in their_addr; // información sobre la dirección del clienteint addr_len, numbytes;char buf[MAXBUFLEN];

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {perror("socket");exit(1);}

Page 265: Operating Systems User Interfaces

[Servidor Datagrama@Unidad I]$my_addr.sin_family = AF_INET; // Ordenación de bytes de máquinamy_addr.sin_port = htons(MYPORT); // short, Ordenación de bytes de la redmy_addr.sin_addr.s_addr = INADDR_ANY; // rellenar con mi dirección IPmemset(&(my_addr.sin_zero), '\0', 8); // poner a cero el resto de la estructura

if (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1) {perror("bind");exit(1);}

addr_len = sizeof(struct sockaddr);if ((numbytes=recvfrom(sockfd,buf, MAXBUFLEN-1, 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {perror("recvfrom");exit(1);}

printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr));printf("packet is %d bytes long\n",numbytes);buf[numbytes] = '\0';printf("packet contains \"%s\"\n",buf);

close(sockfd);

return 0;}

Page 266: Operating Systems User Interfaces

[Cliente Datagrama@Unidad I]$#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>

#define MYPORT 4950 // puerto donde vamos a conectarnos

int main(int argc, char *argv[]){int sockfd;struct sockaddr_in their_addr; // información sobre la dirección del servidorstruct hostent *he;int numbytes;

if (argc != 3) {fprintf(stderr,"usage: talker hostname message\n");exit(1);}

if ((he=gethostbyname(argv[1])) == NULL) { // obtener información de máquinaperror("gethostbyname");exit(1);}

Page 267: Operating Systems User Interfaces

[Cliente Datagrama@Unidad I]$if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {perror("socket");exit(1);}

their_addr.sin_family = AF_INET; // Ordenación de bytes de máquinatheir_addr.sin_port = htons(MYPORT); // short, Ordenación de bytes de la redtheir_addr.sin_addr = *((struct in_addr *)he->h_addr);memset(&(their_addr.sin_zero), '\0', 8); // poner a cero el resto de la estructura

if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0,(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) {perror("sendto");exit(1);}

printf("sent %d bytes to %s\n", numbytes,inet_ntoa(their_addr.sin_addr));

close(sockfd);

return 0;}

Page 268: Operating Systems User Interfaces

[Servidor Stream@Unidad I]$import java.net.*;import java.io.*;

public class SocketServidor{ public static void main (String [] args) {

new SocketServidor();

} public SocketServidor() { try {

ServerSocket socket = new ServerSocket (35557);

System.out.println ("Esperando cliente"); Socket cliente = socket.accept(); System.out.println ("Conectado con cliente de " + cliente.getInetAddress());

cliente.setSoLinger (true, 10);

DataOutputStream buffer = new DataOutputStream (cliente.getOutputStream());

Page 269: Operating Systems User Interfaces

[Servidor Stream@Unidad I]$ buffer.writeInt (22); System.out.println ("Enviado 22"); buffer.writeUTF ("Hola"); System.out.println ("Enviado Hola");

DatoSocket dato = new DatoSocket(); ObjectOutputStream bufferObjetos = new ObjectOutputStream (cliente.getOutputStream());

bufferObjetos.writeObject(dato); System.out.println ("Enviado " + dato.toString());

cliente.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } }}

Page 270: Operating Systems User Interfaces

[Cliente Stream@Unidad I]$import java.net.*;import java.io.*;

public class SocketCliente { public static void main (String [] args) { new SocketCliente(); } public SocketCliente() { try {

Socket socket = new Socket ("localhost", 35557); System.out.println ("conectado");

Page 271: Operating Systems User Interfaces

[Cliente Stream@Unidad I]$DataInputStream buffer = new DataInputStream (socket.getInputStream());

System.out.println("Recibido " + buffer.readInt());

System.out.println ("Recibido " + buffer.readUTF());

ObjectInputStream bufferObjetos = new ObjectInputStream (socket.getInputStream());

DatoSocket dato = (DatoSocket)bufferObjetos.readObject(); System.out.println ("Recibido " + dato.toString()); } catch (Exception e) { e.printStackTrace(); } }}

Page 272: Operating Systems User Interfaces

[Procesos@Unidad I]$#include <sys/types.h>#include <signal.h>#include <unistd.h>

void trataSenhal (int);main(){

pid_t idProceso;

idProceso = fork();

if (idProceso == -1){

perror ("No se puede lanzar proceso");exit (-1);

}

Page 273: Operating Systems User Interfaces

[Procesos@Unidad I]$if (idProceso == 0){

signal (SIGUSR1, trataSenhal);while (1)pause ();

}

if (idProceso > 0){

while (1){

sleep (1);kill (idProceso, SIGUSR1);

}}

}

void trataSenhal (int numeroSenhal){

printf ("Recibida señal del padre\n");}

Page 274: Operating Systems User Interfaces

[Semáforos@Unidad I]$#include <iostream.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <stdlib.h>

#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)#elseunion semun {

int val;struct semid_ds *buf;unsigned short int *array;struct seminfo *__buf;

};#endif

Page 275: Operating Systems User Interfaces

[Semáforos@Unidad I]$main(){

key_t Clave;int Id_Semaforo;struct sembuf Operacion;union semun arg;int i=0;

Clave = ftok ("/bin/ls", 33);if (Clave == (key_t)-1){

cout << "No puedo conseguir clave de semáforo" << endl;exit(0);

}

Id_Semaforo = semget (Clave, 10, 0600 | IPC_CREAT);

Page 276: Operating Systems User Interfaces

[Semáforos@Unidad I]$if (Id_Semaforo == -1){

cout << "No puedo crear semáforo" << endl;exit (0);

}

arg.val = 0;semctl (Id_Semaforo, 0, SETVAL, &arg);

Operacion.sem_num = 0;Operacion.sem_op = -1;Operacion.sem_flg = 0;

while (1){

cout << i << " Esperando Semáforo" << endl;semop (Id_Semaforo, &Operacion, 1);cout << i << " Salgo de Semáforo " << endl;cout << endl;i++;

}}

Page 277: Operating Systems User Interfaces

[RPC@Unidad I]$• rpcgen -a fichero.x

program  NOMBRE_PROGRAMA {     version VERSION_PROGRAMA {         int incrementa (int) = 1;     } = 1; } = 0x20000001;

Page 278: Operating Systems User Interfaces

[RPC@Unidad I]$• int suma (int sumando1, int sumando2);

• struct sumandos {      int sumando1;      int sumando2; };

• program PROGRAMA_SUMA {

    version VERSION_SUMA {         int suma (sumandos) = 1;     } = 1; } = 0x20000001;

Page 279: Operating Systems User Interfaces

[RPC@Unidad I]$int * suma_1_svc(sumandos *argp, struct svc_req

*rqstp) {             static int  result;            

/*             * insert server code here             */             result = argp->sumando1 + argp->sumando2;

/* Esta línea debe hacerla el programador */             return &result; }

Page 280: Operating Systems User Interfaces

[RMIi@Unidad I]$import java.rmi.*;

public interface HolaMundoRmiI extends Remote {

String objRemotoHola( String cliente ) throws RemoteException;

}

Page 281: Operating Systems User Interfaces

[RMIc@Unidad I]$import java.rmi.*;

public class HolaMundoRmiC {

public static void main( String[] args ) { // Direccion de la maquina remota, en este caso la maquina local, // si se va a ejecutar en una maquina diferente, se debera cambiar // a algo semejante a: "rmi://www.servidor.com" String direccion = "rmi://10.27.34.47/"; try { HolaMundoRmiI hm = (HolaMundoRmiI)Naming.lookup( direccion+"ObjetoHola" ); System.out.println( hm.objRemotoHola( "Mundo" ) ); } catch( Exception e ) { e.printStackTrace(); } System.exit( 0 ); }}

Page 282: Operating Systems User Interfaces

[RMIs@Unidad I]$import java.rmi.*;import java.rmi.server.*;

public class HolaMundoRmiS {

public static void main( String args[] ) {

try { // Se instala el controlador de seguridad if( System.getSecurityManager() == null ) { System.setSecurityManager( new RMISecurityManager() ); }

HolaMundoRmiO objRemoto = new HolaMundoRmiO();

Naming.rebind( "ObjetoHola",objRemoto );

System.out.println( "Objeto remoto preparado" ); } catch( Exception e ) { e.printStackTrace(); } } }

Page 283: Operating Systems User Interfaces

[RMIo@Unidad I]$import java.rmi.*;import java.rmi.server.*;

public class HolaMundoRmiO extends UnicastRemoteObject implements HolaMundoRmiI {

// Constructor del objeto remoto public HolaMundoRmiO() throws RemoteException { super(); }

public String objRemotoHola( String cliente ) throws RemoteException { return( "Hola "+cliente ); } }

Page 284: Operating Systems User Interfaces

[Perl@Unidad I]$• #!/usr/bin/perl -w• # 531-byte qrpff-fast, Keith Winstein and Marc Horowitz <[email protected]>• # MPEG 2 PS VOB file on stdin -> descrambled output on stdout• # arguments: title key bytes in least to most-significant order• $_='while(read+STDIN,$_,2048){$a=29;$b=73;$c=142;$t=255;@t=map{$_

%16or$t^=$c^=(• $m=(11,10,116,100,11,122,20,100)[$_/16%8])&110;$t^=(72,@z=(64,72,$a^=12*($_

%16• -2?0:$m&17)),$b^=$_%64?12:0,@z)[$_%8]}(16..271);if((@a=unx"C*",$_)[20]&48){$h• =5;$_=unxb24,join"",@b=map{xB8,unxb8,chr($_^$a[--$h+84])}@ARGV;s/...$/1$&/;$• d=unxV,xb25,$_;$e=256|(ord$b[4])<<9|ord$b[3];$d=$d>>8^($f=$t&($d>>12^$d>>4^• $d^$d/8))<<17,$e=$e>>8^($t&($g=($q=$e>>14&7^$e)^$q*8^$q<<6))<<9,$_=$t[$_]^• (($h>>=8)+=$f+(~$g&$t))for@a[128..$#a]}print+x"C*",@a}';s/x/pack+/g;eval

Page 285: Operating Systems User Interfaces

[Usuarios@Unidad II]$• La representación de alguien (persona o

proceso) que pueden trabajar en el sistema. P.ej. : root, postgresql, jcolivar, fmorales.

• Cada usuario posee:– tiene un login– directorio base $HOME:/home/dsc/jcolivar.– grupo, por ejemplo: users, root.– perfil, bash_profile

Page 286: Operating Systems User Interfaces

[Usuarios@Unidad II]$• useradd agrega usuario• adduser useradd interactivo• userdel borra usuarios• usermod modifica usuarios

• groupadd agrega grupos• groupdel borra grupos• groupmode modifica grupos

Page 287: Operating Systems User Interfaces

[Usuarios@Unidad II]$• passwd cambiar contraseña• login entrar al sistema

• who lista los usuarios del sistema• w versión especial del listado de usuarios• whoami indica el usuario actual

Page 288: Operating Systems User Interfaces

[Usuarios@Unidad II]$• Linux no soporta Listas de Control de Acceso

ACL

• Contraseñas seguras son aquellas que no pertenecen a ningún idioma, contienen números y signo de puntuación.

• Las contraseñas están cifradas.

Page 289: Operating Systems User Interfaces

[/etc/passwd@Unidad II]$• gandalf::501:100:Eric Dumas:/home/gandalf:/bin/bash

sgandalf::0:0:Super Eric Dumas:/:/bin/sh

• Nombre del usuario: 8 caracteres máximo* • Contraseña codificada • Número de identificación único del usuario (uid). Nota: 0 = root• Numero del grupo (gid)• Nombre "oficial" del usuario (llamado GECOS) • Directorio raíz del usuario • Intérprete de órdenes utilizado

Page 290: Operating Systems User Interfaces

[useradd@Unidad II]$• -c comment• -d homedir• -e expire-date• -f inactive-time tiempo de expiración de cuenta• -g initial_roup• -G group• -m directorio home• -M no crear directorio home• -s shell• -u uid

Page 291: Operating Systems User Interfaces

[/etc/group@Unidad II]$root:x:0:rootbin:x:1:root,bin,daemontty:x:5:disk:x:6:rootlp:x:7:daemon,lpmail:x:12:mailnews:x:13:newsuucp:x:14:uucpnobody:x:99:users:x:100

Page 292: Operating Systems User Interfaces

[Quotas@Unidad II]$• Kernel: options QUOTA

• archivo /etc/sysconfig (quotas=yes|no) • check_quotas=YES

• /etc/fstab • userquota • /dev/sd1s2g /home ufs rw, userquota 1 2

Page 293: Operating Systems User Interfaces

[Quotas@Unidad II]$• /dev/sd1s2g/homeufs rw, userquota,

groupquota 1 2

• quota.user y quota.group • quotacheck, quotaon, o quotaoff

• quota -v • edquota -u test

Page 294: Operating Systems User Interfaces

[Shell@Unidad II]$• /etc/shells• .archivo archivo oculto

• Cambio de contraseña con * a4dd89k*motivo de la cancelación

• /etc/inetd.conf

Page 295: Operating Systems User Interfaces

[Shell@Unidad II]$• export exporta variable de ambiente• env ambiente• set configura variable de ambiente • history historial

• shutdown apagar la máquina• poweroff apagar la máquina• halt apagar la máquina• reboot reiniciar la máquina

Page 296: Operating Systems User Interfaces

[Shell@Unidad II]$• unset variable• ls -l; cat /etc/passwd• -l• -a• -1• -r

• /usr/bin/loadkeys• /usr/lib/kdb/keytables/es.map

Page 297: Operating Systems User Interfaces

[Shell@Unidad II]$• kill mata procesos• ps estado de los procesos• nice aumentar prioridad de procesos • nohup no dejar colgado un proceso

• sleep dormir proceso • wake despertar proceso • awake

Page 298: Operating Systems User Interfaces

[Shell@Unidad II]$• ps

• -a todos los procesos con el terminal controlado, excepto el proceso de usuario actual.

• -r ejecución• -x procesos sin terminal controlado• -l formato largo

Page 299: Operating Systems User Interfaces

[Shell@Unidad II]$• top visor de procesos• uname -a -r

• /etc/rc.d/init.d/• /etc/init.d

• Anaconda• Kudzu

Page 300: Operating Systems User Interfaces

[Shell@Unidad II]$• chmod cambiar permisos de archivos• chown cambiar dueños de archivos• chgrp cambiar grupo de los archivos

• mkfs formatear sistema de archivo• printenv ver variables de entorno• sync vaciar búfer de sistemas de archivo

Page 301: Operating Systems User Interfaces

[Shell@Unidad II]$• pwd directorio actual• cp copiar archivos• rm borrar archivos• mv mover archivos• * todos los caracteres• ? Un solo caracter• > redireccionar la salida• cat • < redireccionar la entrada

Page 302: Operating Systems User Interfaces

[Shell@Unidad II]$• mv, cp• -f forzar -i interactivo

• mknod /tmp/mi_pipe p• which ls

• setup• linuxconf• netconf

Page 303: Operating Systems User Interfaces

[Shell@Unidad II]$• | tuberías• & proceso en segundo plano

• touch actualiza archivo• du espacio ocupado por directorio• df muestra el espacio ocupado por cada

sistema de archivo• uptime fecha y tiempo activo

Page 304: Operating Systems User Interfaces

[Shell@Unidad II]$• more ver archivos largos• less ver archivos largos interactivo• head muestra las primeras 10 líneas de un

archivo• tail muestra las últimas 10 líneas de un archivo• file identifica tipo de archivo• grep búsqueda de patrones

Page 305: Operating Systems User Interfaces

[Shell@Unidad II]$• wc cuenta el número de palabras, líneas,

caracteres de un archivo• spell, ispell ortografía• cmp compara dos archivos• diff muestra las diferencias de dos archivos

• gzip comprimir archivo• gunzip descomprimir archivo

Page 306: Operating Systems User Interfaces

[Shell@Unidad II]$• tr traductor cambia palabras de un archivo por

otro• mail envío de correo• finger información sobre usuarios• find busca archivos• test realiza comparaciones • dd duplicador de datos

Page 307: Operating Systems User Interfaces

[Shell@Unidad II]$• fg trae a primer plano un proceso• jobs muestra los trabajos en el sistema• bg manda un proceso a segundo plano• Ctrl+c interrupción• Ctrl+z suspender

• clear borra pantalla• date fecha• man manuales

Page 308: Operating Systems User Interfaces

[Shell@Unidad II]$• mc shell visual• cal calendario

• vi editor de texto • pico editor de texto y correo• ed editor de texto en una línea• joe editor de texto

Page 309: Operating Systems User Interfaces

[Shell@Unidad II]$• su cambia de usuario• sudo ejecutar un comando en nombre a tu

usuario• ln (ln -s links lynx) enlaces

• rmdir borra un directorio• mkdir crea un directorio

Page 310: Operating Systems User Interfaces

[Shell@Unidad II]$• cut quita tablas de un archivo• read var captura el valor de una variable• sort ordena las líneas de un archivo• uniq borra líneas duplicadas sucesivas

• sed y awk programas de procesamiento de patrones

Page 311: Operating Systems User Interfaces

[Shell@Unidad II]$• sum verifica la suma de comprobación• md5sum suma de comprobación

• fsck hace una revisa al sistema de archivo• cpio copiado de archivos a bajo nivel

• write escribe un mensaje a un usuario • talk plática

Page 312: Operating Systems User Interfaces

[Shell@Unidad II]$• mount monta sistema de archivos• umount desmonta dispositivo

• mount -a monta todos los sistemas de archivos de /etc/fstab

• -t ext2, FAT, VFAT, FAT32

Page 313: Operating Systems User Interfaces

[Shell@Unidad II]$• Opciones de mount

• ro read only• rw read write• exec • noauto no monta de manera automática• e2fsck• lost + found

Page 314: Operating Systems User Interfaces

[Shell@Unidad II]$$1 - $9 parámetros$0 nombre del comando actual $# número de parámetros $? status del último comando ejecutado dado como un string

decimal. $$ el número de proceso de este shell$! el pid del último comando ejecutado en background.$- las opciones actuales suministradas para esta invocación del

shell. $* $@@ un string que contiene todos los argumentos del shell

comenzando por el $1.

Page 315: Operating Systems User Interfaces

[Shell@Unidad II]$• sh -x script argument • Cambiar permisos al script de ejecución y firmarlo

• ‘’ Literal simple• `` Sustituir valor de la variable• “” Sustituir por lo que haya en las comillas• Shift avanzar parametros

• test []• echo• && ||

Page 316: Operating Systems User Interfaces

[Shell@Unidad II]$• test

• -d directorio • -e archivo sin importar el tipo • -f archivo normal • -r leer archivo • -s tamaño mayor que 0 • -w escribir archivo• -x archivo ejecutable • -eq iguales • -ne no son iguales

Page 317: Operating Systems User Interfaces

[Shell@Unidad II]$• -gt mayor • -ge mayor o igual • -lt menor • -le menor o igual • = cadenas idénticas • != cadenas no son idénticas • < menor • > mayor • -n longitud de la cadena de texto es distinta de cero • ! Negación• -a and• -o or

Page 318: Operating Systems User Interfaces

[Shell@Unidad II]$/etc/crontab# hacer una copia de seguridad todos los lunes a las 2 de la

mañana 0 2 * * 1 /home/gandalf/backup # Reiniciar la máquina todos los 1 y 15 de cada mes a la 4:15 15

4 1,15 * * /sbin/shutdown -r +3

• Las 5 primeras columnas son : – Minutos (0 a 59) ; – Hora (0 a 23) ; – Día del mes (1 a 31) ; – Mes (1 a 12) ; – Día de la semana (0 a 6 : 0 = Domingo, 1 = Lunes).

Page 319: Operating Systems User Interfaces

[Shell@Unidad II]$• Banner muestra un mensaje

• _nombre_funcion_ () { _lista_de_ordenes_ }

• whereis

• awk '{print $1}' fichero

• sed s/tomate/pera/g a.txt > b.txt

Page 320: Operating Systems User Interfaces

[Shell@Unidad II]$• if ....; • then .... • elif ....; • then .... • else .... • fi

• [ -f "/etc/shadow" ] && echo "Este ordenador usa shadow passwors"

Page 321: Operating Systems User Interfaces

[Shell@Unidad II]$case ... in ...)

hacer algo aquí;; esac

while ...; do .... done

for var in ....; do .... done

Page 322: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/shtest -x /home/www/bin/httpd || exit 0

case "$1" in #cuál fue el parámetro de invocación

start)echo -n "Iniciando servidor http"start-stop-daemon --start --quiet --pidfile /var/run/httpd.pid \--exec /home/www/bin/httpdecho "."

;;stop)

echo -n "Deteniendo servidor httpd"start-stop-daemon --stop --quiet --pidfile /var/run/httpd.pidecho "."

;;

Page 323: Operating Systems User Interfaces

[Shell@Unidad II]$restart)

/etc/init.d/httpd stopsleep 2/etc/init.d/httpd startecho "."

;;*)

echo "Uso: /etc/init.d/httpd {start|stop|restart}"exit 1

esacexit 0

Page 324: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/sh if [ "$SHELL" = "/bin/bash” ]; then

echo "tu shell es el bash (bourne again shell)“else

echo "tu shell no es bash sino $SHELL" fi

Page 325: Operating Systems User Interfaces

[Shell@Unidad II]$# /etc/profile# System wide environment and startup programs# Functions and aliases go in /etc/bashrc

if ! echo $PATH | /bin/grep -q "/usr/X11R6/bin" ; then PATH="$PATH:/usr/X11R6/bin"fi

USER=`id -un`LOGNAME=$USERMAIL="/var/spool/mail/$USER"

HOSTNAME=`/bin/hostname`HISTSIZE=1000

Page 326: Operating Systems User Interfaces

[Shell@Unidad II]$do

echo $i i=$(($i+1)) done

# lee de stdin hasta que se introduzca 'quit' read linea

while [ "$linea" != "quit" ];

Page 327: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/sh#Pograma que borra todos los archivos (correos) que contienen la

palabra 'To: jazarate'

if [ -d cd /var/mail ]then

grep -l "To:" * | xargs rmecho "Se borraron los archivos solicitados"

elseecho "Imposible borrar, no existe el directorio de correo"

fi

Page 328: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/sh#Programa que calcula cuantos usuarios hay en

el sistema

echo "Numero de usuarios en el sistema: `who | awk '{print $1}' | sort -u | wc -l`"

Page 329: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/sh#Script en shell de linux que calcula el usuario que tiene mas correos en el

sistema

if [ -d /var/mail ]then

cd /var/maila=`grep -r -c "Message-ID" * | awk 'BEGIN{FS=":"}{ print $2}' | sort -g -r | awk '{getline X ;print $1}'`

clearecho "El usuario con mas correo es: `grep -r -c "Message-ID" * | grep $a | awk 'BEGIN{FS=":"}{ print $1}'`"

else # No hay spool de correo en el sistema, salirecho "Lo sentimos pero no existe servidor de correo o no se encontro"

fi

Page 330: Operating Systems User Interfaces

[Shell@Unidad II]$#!/bin/sh#Shell que crea un usuario pasando el nombre como parámetro

asi como su directorio public html

if [ $# -eq 1 ]then #creamos el nuevo usuario

useradd $1mkdir /home/$1cd /home/$1mkdir public_html

elseecho "!Sintaxis incorrecta!. Uso correcto: $0 nombre_usuario"

fi

Page 331: Operating Systems User Interfaces

[Arranque@Unidad II]$• El hardware lee el sector de arranque• Se carga LILO/GRUB

• Se carga el Kernel

• Se monta el sistema de archivos raíz• Se inicia init, el abuelo de todos los procesos• Se lee /etc/inittab

Page 332: Operating Systems User Interfaces

[Arranque@Unidad II]$• Ejecuta todos los scripts de nivel 1

• El final del nivel 1 indica que se vaya a 3

• Ejecuta todos los scripts de nivel 3

• El sistema está listo para usarse (se deberá autenticar para acceder al sistema)

Page 333: Operating Systems User Interfaces

[LILO@Unidad II]$• LInux LOader, es el cargador del Kernel más

común para Linux• Uso casi exclusivo para arranques desde disco

duro

• Configuración en /etc/lilo.conf• Cargador en sector de arranque y en /boot/map

Page 334: Operating Systems User Interfaces

[Configuración LILO@Unidad II]Default = linuxBoot =/dev/hdaPromptTimeout = 50Image=/boot/vmlinuz-2.2.5-15

Label = linuxRoot = /dev/hda2Read-only

Other =/dev/hda1label = DOStable = /dev/hda

Page 335: Operating Systems User Interfaces

[grub@Unidad II]$• GRand Unified Bootloader, es el cargador del

Proyecto GNU• Muy versátil y configurable, permite arrancar

casi cualquier sistema operativo• Entiende internamente FAT, ext2, Reiser,

JFS. . .

• Configuración en /boot/grub/menu.lst.

Page 336: Operating Systems User Interfaces

[Configuración GRUB@Unidad II]$title Debian GNU/Linuxroot (hd0,1)kernel /boot/vmlinuz root=/dev/hda1 ro

title Debian GNU/Linux, kernel 2.6.10root (hd0,1)kernel /boot/vmlinuz-2.6.10 root=/dev/hda1 ro

Page 337: Operating Systems User Interfaces

[Otros cargadores@Unidad II]$• SYSLINUX/ISOLINUX orientado a arranques

desde floppy y cd.

• Arrancar en red (DHCP y TFTP). PXELINUX, ETHERBOOT, COMBOOT.

Page 338: Operating Systems User Interfaces

[init@ Unidad II]$• Primer proceso del sistema.• PID=1 (siempre).• “Padre de todos los procesos”.• Adopta y recoge a todos los procesos

huérfanos.• No se puede morir.• Archivo de configuración: /etc/inittab• Niveles de ejecución: “runlevels”.

Page 339: Operating Systems User Interfaces

[/etc/inittab@Unidad II]$• 0 Sistema

• 1 Monousuario• 2 Multiusuario sin NFS

• 3 Operación Normal• 4 Sin uso

• 5 Mismo que 3 pero con X Windows• 6 Rearranque del sistema

Page 340: Operating Systems User Interfaces

[Scripts rc@Unidad II]$• /etc/rc.d/rc3.d• /etc/rc.d/initd• S arranca servicio• K parar

• lrwxrwxrwx   1 root root    9 Oct 20 20:05 K24random -> ../init.d/randomlrwxrwxrwx   1 root root    8 Oct 20 18:23 S01fbset -> ../init.d/fbset

• service servicio start | stop | restart | satus

Page 341: Operating Systems User Interfaces

[/etc/rc.d/rc.local@Unidad II]$ #! /bin/sh #Limpia de archivos temporales

echo “Eliminando archivos temporales..." find /tmp -type f -mtime +1 | xargs -r rm find /tmp -type d -mtime +1 | xargs -r rmdir

Page 342: Operating Systems User Interfaces

[Autenticación@Unidad I]$• La aplicación pide una contraseña al usuario• Se comprueba /etc/nsswitch.conf para ver

donde está la contraseña• Se lee /etc/passwd /etc/shadow• Se comprueba esa entrada• La aplicación compara las cadenas y si son

iguales se tiene acceso

Page 343: Operating Systems User Interfaces

[Login@Unidad II]$• Login: usuario• Pasword: ******

• [roge@antares /home/roge]$• [root@antares /root]#

• [root@antares /root]# logout • [root@antares /root]# shutdown now

Page 344: Operating Systems User Interfaces

[Parada@Unidad I]$• Se invoca al comando shutdown o reboot• Se llama init para cambiar el nivel de ejecución

a 6• Se ejecutan los scripts del nivel 6 con stop• Los búferes de salida se escriben en disco

(sync)• Los sistemas de archivos se desmontan• El sistema se para

Page 345: Operating Systems User Interfaces

[Sistema de archivos@Unidad II]$• Nativo linux ext2• Intercambio de memoria swap• CD-ROM iso9660• Monitorización del sistema proc• Sistema de archivos de red (NFS) nfs• FAT básico msdos• VFAT (Windows 95) vfat• Minix minix• System V sysv• BSD Fast File System bsd

Page 346: Operating Systems User Interfaces

[Árbol de directorios@Unidad II]$• /bin binarios• /sbin binarios de root• /dev dispositivos• /etc archivos de configuración• /home archivos de usuarios• /proc archivos del kernel• /tmp archivos temporales

Page 347: Operating Systems User Interfaces

[Árbol de directorios@Unidad• /boot Imágenes del kernel• /mnt montaje de directorios (/floppy, /cdrom)• /lib Bibliotecas y módulos• /root información sobre el administrador• /usr programas• /var bitácoras del sistema

Page 348: Operating Systems User Interfaces

[/proc@Unidad II]$• /proc/cpuinfo tipo de CPU• /proc/interrupts tabla IRQ• /proc/meminfo información sobre la memoria• /proc/modules igual que lsmod• /proc/pci periféricos con soporte PCI• /proc/net/arp tabla ARP• /proc/net/dev dispositivos de red

Page 349: Operating Systems User Interfaces

[Dispositivos de bloque@Unidad II]$• Brw-rw----- 1 root disk 3, 0 May 5 1998

/dev/hda

• 3 major number• 0 minor number• 3 controlador de dispositivo pero diferente

puerto

Page 350: Operating Systems User Interfaces

[Dispositivo de caracter@Unidad II]$• Crw--------- 1 root tty 4, 64 May 5 1998

/dev/ttyS0

• P pipe

• R Lectura 4• W Escritura 2• X Ejecución 1

Page 351: Operating Systems User Interfaces

[Kernel@Unidad II]$• Búsqueda e inicialización de hardware.• Inicialización de la pila TCP/IP.• Monta sistema de ficheros raíz (“root

filesystem”).• Prepara la consola, terminales virtuales, etc.• Ejecuta el primer proceso del sistema,

“/sbin/init”.

Page 352: Operating Systems User Interfaces

[Mensajes del kernel]@Unidad II• Todos los mensajes que genera el kernel se

pueden ver con la orden “dmesg”.

• dmesg | grep quotas

VFS: Diskquotas version dquot_5.6.0 initialized

Page 353: Operating Systems User Interfaces

[Kernel@Unidad II]$• Impar inestable 2.1, 2.3• Par estable 2.0, 2.2• Última versión estable 2.6.19.2 (13/01/2006)

• /etc/src/linux

• Desempacar el kernel.

• make xconfig gráfico

Page 354: Operating Systems User Interfaces

[Configuración Kernel@Unidad II]$• Al Kernel se le pueden pasar una serie de

parámetros para:– Configurar dispositivos (discos duros, tarjetas de

red, puertos serie, memoria (mem=XXX). . . )– Indicar sistema de archivos raíz (root=/dev/XXX)– Condiciones especiales: monousuario, distinto init

(init=XXX). . .– Cada cargador tiene su manera de pasarle

parámetros al Kernel– Dentro del Kernel, los parámetros con los que se ha

arrancado se pueden ver en /proc/cmdline

Page 355: Operating Systems User Interfaces

[Configuración Kernel@Unidad II]$• LILO linux single modo usuario• LILO mem=128

• GRUB kernel (hd0,0)/vmlinuz root=/dev/hda1 single

• modconf asistente para módulos• lsmod, rmmod, insmod, depmod, modprobe

Page 356: Operating Systems User Interfaces

[Instalación del Kernel@Unidad II]• make config• make xconfig

• Escoger los módulos y opciones a instalar

• make dep; make clean; make zImage; make modules; make modules_install

Page 357: Operating Systems User Interfaces

[Instalación@Unidad II]$• make bzImage

• Kernel compilado: /usr/src/linux/arch/i386/boot/zImage,

• Mapas: /usr/src/linux/System.map

• /boot/vmlinuz-x.x.x• System.map mensajes

Page 358: Operating Systems User Interfaces

[Cargador de arranque@Unidad II]$Default=/boot/vmlinuz-x.x.xImage=/boot/vmlinuz-x.x.xLabel= Linux compiladoRoot=/dev/hda1

• Parcheado del kernel• Patch –p0 < parche-2.2.11

Page 359: Operating Systems User Interfaces

[Seguridad@Unidad II]$• La seguridad viene inmersa dentro de cada

aplicación o en su defecto.

• Verificar siempre los logs del sistema• Tener actualizado siempre los sistemas con las

últimas alertas de seguridad.

• No existen sistemas completamente seguros

Page 360: Operating Systems User Interfaces

[Seguridad@Unidad II]$• Configurar adecuadamente los permisos de

archivos para todos los usuarios• Configurar contraseñas cambiantes• No utilizar la cuenta de root como usuario• Utilizar enlaces simbólicos y espacio de cuotas

para los usuarios• No activar servicios que no se utilicen• Cerrar todos los puertos

Page 361: Operating Systems User Interfaces

[Seguridad@Unidad II]$• No instalar GUIs a menos que sea

extremadamente necesario.• Instale un Firewall vía SW o HW• Utilizar protocolos cifrados: HTTPS, SFTP,

SSH, etc.• Hacer respaldo de la información

constanteente

Page 362: Operating Systems User Interfaces

362

Comparing the Architectures• Both Linux and Windows are monolithic

– All core operating system services run in a shared address space in kernel-mode

– All core operating system services are part of a single module• Linux: vmlinuz • Windows: ntoskrnl.exe

• Windowing is handled differently:– Windows has a kernel-mode Windowing subsystem– Linux has a user-mode X-Windowing system

Page 363: Operating Systems User Interfaces

363

Kernel Architectures

Device Drivers

Process Management, Memory Management, I/O Management, etc.

X-Windows

Application

System Services

User ModeKernel Mode

Hardware Dependent Code

Linux

Device Drivers

Process Management, Memory Management, I/O Management, etc.

Win32Windowing

Application

System Services

User ModeKernel Mode

Hardware Dependent Code

Windows

Page 364: Operating Systems User Interfaces

364

Linux Kernel

• Linux is a monolithic but modular system– All kernel subsystems form a single piece of code with no

protection between them• Modularity is supported in two ways:

– Compile-time options– Most kernel components can be built as a dynamically loadable

kernel module (DLKM)• DLKMs

– Built separately from the main kernel – Loaded into the kernel at runtime and on demand (infrequently

used components take up kernel memory only when needed)– Kernel modules can be upgraded incrementally– Support for minimal kernels that automatically adapt to the

machine and load only those kernel components that are used

Page 365: Operating Systems User Interfaces

365

Windows Kernel• Windows is a monolithic but modular system

– No protection among pieces of kernel code and drivers• Support for Modularity is somewhat weak:

– Windows Drivers allow for dynamic extension of kernel functionality

– Windows XP Embedded has special tools / packaging rules that allow coarse-grained configuration of the OS

• Windows Drivers are dynamically loadable kernel modules– Significant amount of code run as drivers (including network stacks

such as TCP/IP and many services)– Built independently from the kernel– Can be loaded on-demand– Dependencies among drivers can be specified

Page 366: Operating Systems User Interfaces

366

Comparing Portability• Both Linux and Windows kernels are portable

– Mainly written in C– Have been ported to a range of processor architectures

• Windows– i486, MIPS, PowerPC, Alpha, IA-64, x86-64– Only x86-64 and IA-64 currently supported– > 64MB memory required

• Linux– Alpha, ARM, ARM26, CRIS, H8300, i386, IA-64, M68000, MIPS, PA-

RISC, PowerPC, S/390, SuperH, SPARC, VAX, v850, x86-64– DLKMs allow for minimal kernels for microcontrollers– > 4MB memory required

Page 367: Operating Systems User Interfaces

367

Comparing Layering, APIs, Complexity• Windows

– Kernel exports about 250 system calls (accessed via ntdll.dll)– Layered Windows/POSIX subsystems – Rich Windows API (17 500 functions on top of native APIs)

• Linux– Kernel supports about 200 different system calls– Layered BSD, Unix Sys V, POSIX shared system libraries– Compact APIs (1742 functions in Single Unix Specification Version 3; not

including X Window APIs)

Page 368: Operating Systems User Interfaces

368

Comparing Architectures

• Processes and scheduling• SMP support• Memory management• I/O• File Caching• Security

Page 369: Operating Systems User Interfaces

369

Process ManagementWindows• Process

– Address space, handle table, statistics and at least one thread

– No inherent parent/child relationship

• Threads– Basic scheduling unit– Fibers - cooperative user-mode

threads

LinuxLinux

Process is called a TaskProcess is called a Task

Basic Address space, Basic Address space, handle table, statisticshandle table, statistics

Parent/child relationshipParent/child relationship

Basic scheduling unitBasic scheduling unit

ThreadsThreads

No threads per-seNo threads per-se

Tasks can act like Windows Tasks can act like Windows threads by sharing handle threads by sharing handle table, PID and address table, PID and address spacespace

PThreads – cooperative PThreads – cooperative user-mode threadsuser-mode threads

Page 370: Operating Systems User Interfaces

370

Scheduling PrioritiesWindows• Two scheduling classes

– “Real time” (fixed) - priority 16-31

– Dynamic - priority 1-15• Higher priorities are

favored– Priorities of dynamic

threads get boosted on wakeups

– Thread priorities are never lowered

31

15

16

0

Fixed

DynamicI/O

Windows

Page 371: Operating Systems User Interfaces

371

Scheduling PrioritiesWindows• Two scheduling classes

– “Real time” (fixed) - priority 16-31

– Dynamic - priority 1-15• Higher priorities are

favored– Priorities of dynamic

threads get boosted on wakeups

– Thread priorities are never lowered

LinuxLinuxHas 3 scheduling classes:Has 3 scheduling classes:

Normal – priority 100-139Normal – priority 100-139Fixed Round Robin – priority Fixed Round Robin – priority 0-990-99Fixed FIFO – priority 0-99Fixed FIFO – priority 0-99

Lower priorities are favored Lower priorities are favored Priorities of normal threads Priorities of normal threads go up (decay) as they use go up (decay) as they use CPUCPUPriorities of interactive Priorities of interactive threads go down (boost)threads go down (boost)

Page 372: Operating Systems User Interfaces

372

Scheduling Priorities (cont)

31

15

16

0

Fixed

DynamicI/O

Windows

140

10099

0

Fixed FIFO

Fixed Round-Robin

NormalCPU

I/O

Linux

Page 373: Operating Systems User Interfaces

373

Linux Scheduling Details

• Most threads use a dynamic priority policy – Normal class - similar to the classic UNIX scheduler– A newly created thread starts with a base priority – Threads that block frequently (I/O bound) will have their priority

gradually increased– Threads that always exhaust their time slice (CPU bound) will

have their priority gradually decreased• “Nice value” sets a thread’s base priority

– Larger values = less priority, lower values = higher priority– Valid nice values are in the range of -20 to +20 – Nonprivileged users can only specify positive nice value

• Dynamic priority policy threads have static priority zero – Execute only when there are no runnable real-time threads

Page 374: Operating Systems User Interfaces

374

Real-Time Scheduling on Linux

• Linux supports two static priority scheduling policies:– Round-robin and FIFO (first in, first out)

• Selected with the sched-setscheduler( ) system call• Use static priority values in the range of 1 to 99• Executed strictly in order of decreasing static priority

– FIFO policy lets a thread run to completion • Thread needs to indicate completion by calling the sched-yield( )

– Round-robin lets threads run for up to one time slice • Then switches to the next thread with the same static priority

– RT threads can easily starve lower-prio threads from executing • Root privileges or the CAP-SYS-NICE capability are required for the

selection of a real-time scheduling policy• Long running system calls can cause priority-inversion

• Same as in Windows; but cmp. rtLinux

Page 375: Operating Systems User Interfaces

375

Windows Scheduling Details

• Most threads run in variable priority levels– Priorities 1-15; – A newly created thread starts with a base priority – Threads that complete I/O operations experience priority boosts

(but never higher than 15)– A thread’s priority will never be below base priority

• The Windows API function SetThreadPriority() sets the priority value for a specified thread– This value, together with the priority class of the thread's

process, determines the thread's base priority level– Windows will dynamically adjust priorities for non-realtime

threads

Page 376: Operating Systems User Interfaces

376

Real-Time Scheduling on Windows

• Windows supports static round-robin scheduling policy for threads with priorities in real-time range (16-31)– Threads run for up to one quantum– Quantum is reset to full turn on preemption– Priorities never get boosted

• RT threads can starve important system services– Such as CSRSS.EXE– SeIncreaseBasePriorityPrivilege required to elevate a thread’s

priority into real-time range (this privilege is assigned to members of Administrators group)

• System calls and DPC/APC handling can cause priority inversion

Page 377: Operating Systems User Interfaces

377

Scheduling TimeslicesWindows• The thread timeslice

(quantum) is 10ms-120ms– When quanta can vary, has

one of 2 values

• Reentrant and preemptible

Fixed: 120ms

20ms

Foreground: 60ms

Background

LinuxLinux

The thread quantum is The thread quantum is 10ms-200ms10ms-200ms

Default is 100msDefault is 100ms

Varies across entire range Varies across entire range based on priority, which is based on priority, which is based on interactivity levelbased on interactivity level

Reentrant and Reentrant and preemptible preemptible

100ms

200ms10ms

Page 378: Operating Systems User Interfaces

378

Multiprocessor SupportWindows• Supports symmetric multiprocessing

(SMP)– Up to 32 processors on 32-bit Windows– Up to 64 processors on 64-bit Windows– All CPUs can take interrupts

• Supports Non-Uniform Memory Access systems– Scheduler favors the node a thread

prefers to run on– Memory manager tries to allocate

memory on the node a thread prefers to run on

• Supports Hyperthreading– Scheduler favors idle physical

processors when it has a choice– Doesn’t count logical CPUs against

licensing limitsPhysicalCPU 0

PhysicalCPU 1

0 1 3 4

Ready Thread

Page 379: Operating Systems User Interfaces

379

Multiprocessor SupportWindows• Supports symmetric multiprocessing

(SMP)– Up to 32 processors on 32-bit Windows– Up to 64 processors on 64-bit Windows– All CPUs can take interrupts

• Supports Non-Uniform Memory Access systems– Scheduler favors the node a thread

prefers to run on– Memory manager tries to allocate

memory on the node a thread prefers to run on

• Supports Hyperthreading– Scheduler favors idle physical

processors when it has a choice– Doesn’t count logical CPUs against

licensing limits

LinuxLinux

Supports SMPSupports SMPNo upper CPU limit: set as No upper CPU limit: set as kernel build constantkernel build constant

All CPUs can take interruptsAll CPUs can take interrupts

Supports Non-Uniform Memory Supports Non-Uniform Memory Access systemsAccess systems

Scheduler favors the node a Scheduler favors the node a thread last ran onthread last ran on

Memory manager tries to Memory manager tries to allocate memory on the node a allocate memory on the node a thread is running onthread is running on

Supports HyperthreadingSupports Hyperthreading

Scheduler favors idle Scheduler favors idle physical processors when it physical processors when it has a choicehas a choice

Page 380: Operating Systems User Interfaces

380

Virtual Memory ManagementWindows• 32-bit versions split

user-mode/kernel-mode from 2GB/2GB to 3GB/1GB

• Demand-paged virtual memory– 32 or 64-bits– Copy-on-write– Shared memory– Memory mapped files

User

System

0

2GB

4GB

LinuxLinuxSplits user-mode/kernel-mode Splits user-mode/kernel-mode from 1GB/3GB to 3GB/1GBfrom 1GB/3GB to 3GB/1GB

2.6 has “4/4 split” option where 2.6 has “4/4 split” option where kernel has its own address kernel has its own address spacespace

Demand-paged virtual memoryDemand-paged virtual memory32-bits and/or 64-bits32-bits and/or 64-bitsCopy-on-writeCopy-on-writeShared memoryShared memoryMemory mapped filesMemory mapped files

User

System

0

3GB

4GB

Page 381: Operating Systems User Interfaces

381

Physical Memory ManagementWindows• Per-process working sets

– Working set tuner adjust sets according to memory needs using the “clock” algorithm

• No “swapper”

Process

LRU

Reused Page

LinuxLinux

Global working set managementGlobal working set managementuses “clock” algorithmuses “clock” algorithm

No “swapper” (the working set No “swapper” (the working set trimmer code is called the swap trimmer code is called the swap daemon, however)daemon, however)

LRU

Reused Page

Other ProcessLRU

Page 382: Operating Systems User Interfaces

382

I/O ManagementWindows• Centered around the file object• Layered driver architecture

throughout driver types• Most I/O supports asynchronous

operation• Internal interrupt request level

(IRQL) controls interruptability• Interrupts are split between an

Interrupt Service Routine (ISR) and a Deferred Procedure Call (DPC)

• Supports plug-and-play

LinuxLinuxCentered around the vnodeCentered around the vnodeNo layered I/O modelNo layered I/O modelMost I/O is synchronousMost I/O is synchronous

Only sockets and direct disk Only sockets and direct disk I/O support asynchronous I/O support asynchronous I/OI/O

Internal interrupt request level Internal interrupt request level (IRQL) controls interruptability(IRQL) controls interruptabilityInterrupts are split between an ISR Interrupts are split between an ISR and soft IRQ or taskletand soft IRQ or taskletSupports plug-and-playSupports plug-and-play

IRQLMasked

Page 383: Operating Systems User Interfaces

383

File CachingWindows• Single global common cache• Virtual file cache

– Caching is at file vs. disk block level

– Files are memory mapped into kernel memory

• Cache allows for zero-copy file serving

File Cache

File System Driver

Disk Driver

LinuxLinuxSingle global common cacheSingle global common cache

Virtual file cacheVirtual file cacheCaching is at file vs. disk block Caching is at file vs. disk block levellevel

Files are memory mapped into Files are memory mapped into kernel memory kernel memory

Cache allows for zero-copy file Cache allows for zero-copy file servingserving

File Cache

File System Driver

Disk Driver

Page 384: Operating Systems User Interfaces

384

SecurityWindows• Very flexible security model based on

Access Control Lists• Users are defined with

– Privileges– Member groups

• Security can be applied to any Object Manager object– Files, processes, synchronization

objects, …• Supports auditing

LinuxLinux

Two models: Two models: Standard UNIX modelStandard UNIX model

Access Control Lists (SELinux)Access Control Lists (SELinux)

Users are defined with:Users are defined with:Capabilities (privileges)Capabilities (privileges)

Member groupsMember groups

Security is implemented on an Security is implemented on an object-by-object basisobject-by-object basis

Has no built-in auditing supportHas no built-in auditing support

Version 2.6 includes Linux Security Version 2.6 includes Linux Security Module framework for add-on Module framework for add-on security modelssecurity models

Page 385: Operating Systems User Interfaces

385

Monitoring - Linux procfs• Linux supports a number of special filesystems

– Like special files, they are of a more dynamic nature and tend to have side effects when accessed

• Prime example is procfs (mounted at /proc)

– provides access to and control over various aspects of Linux (I.e.; scheduling and memory management)• /proc/meminfo contains detailed statistics on the current memory usage of Linux• Content changes as memory usage changes over time

• Services for Unix implements procfs on Windows

Page 386: Operating Systems User Interfaces

386

Windows’ Evolution Towards Linux

• Services for Unix 3.5 - really targeted at POSIX, not Linux– POSIX threads, full POSIX subsystem (Interix)– X Window clients+server (X-Win32 LX)– nfs, NIS, pam– proc-file system for Windows

• Configurability / Module Management– Windows XP Embedded– Target Designer/Component Designer/

Component Management Database

• Editions targeting new Application Domains– Windows Compute Cluster Server 2003

POSIX compatibility in Windows actually

predates Linux and was one of the original design

goals

Page 387: Operating Systems User Interfaces

387

Linux’s Evolution Towards Windows

• I/O processing• Kernel reentrancy• Kernel preemptibility• Per-processor memory allocation• O(1) scheduler and per-CPU ready queues• Zero-Copy SendFile• Wake-One socket semantics• Asynchronous I/O• Light-weight synchronization

Page 388: Operating Systems User Interfaces

388

I/O Processing

• Linux 2.2 had the notion of bottom halves (BH) for low-priority interrupt processing– Fixed number of BHs– Only one BH of a given type could be active on a SMP

• Linux 2.4 introduced tasklets, which are non-preemptible procedures called with interrupts enabled

• Tasklets are the equivalent of Windows Deferred Procedure Calls (DPCs)

Page 389: Operating Systems User Interfaces

389

Kernel Reentrancy

• Mark Russinovich’s April 1999 Windows NT Magazine article, “Linux and the Enterprise”, pointed out that much of the Linux 2.2 was not reentrant

• Ingo Molnar stated in rebuttal:– “his example is a clear red herring.”

• A month later he made all major paths reentrant

cpu 1

cpu 2

cpu 1cpu 2

Non-reentrant

Reentrant

Time Saved

Page 390: Operating Systems User Interfaces

390

Kernel Preemptibility

• A preemptible kernel is more responsive to high-priority tasks

• Through the base release of v2.4 Linux was only cooperatively preemptible– There are well-defined safe places where a thread running in the

kernel can be preempted

• The kernel is preemptible in v2.4 patches and v2.6• Windows NT has always been preemptible

Page 391: Operating Systems User Interfaces

391

Per-CPU Memory Allocation

• Keeping accesses to memory localized to a CPU minimizes CPU cache thrashing– Hurts performance on enterprise SMP workloads

• Linux 2.4 introduced per-CPU kernel memory buffers• Windows introduced per-CPU buffers in an NT 4 Service

Pack in 1997

0 1

Buffer Cache 0 Buffer Cache 1

CPUs

Page 392: Operating Systems User Interfaces

392

Scheduling

• The Linux 2.4 scheduler is O(n)– If there are 10 active tasks, it scans 10 of them in a list in order to

decide which should execute next– This means long scans and long durations under the scheduler lock

103 112 112 101ReadyList

Highest PriorityTask

Page 393: Operating Systems User Interfaces

393

Scheduling

• Linux 2.6 has a revamped scheduler that’s O(1) from Ingo Molnar that:– Calculates a task’s priority at the time it makes scheduling decision– Has per-CPU ready queues where the tasks are pre-sorted by priority

112 112

101

103

Highest-priorityNon-empty Queue

Page 394: Operating Systems User Interfaces

394

Scheduling• Windows NT has always had an O(1) scheduler based on pre-

sorted thread priority queues• Server 2003 introduced per-CPU ready queues

– Linux load balances queues – Windows does not

• Not seen as an issue in performance testing by Microsoft• Applications where it might be an issue are expected to use affinity

Page 395: Operating Systems User Interfaces

395

Zero-Copy Sendfile

• Linux 2.2 introduced Sendfile to efficiently send file data over a socket– I pointed out that the initial implementation incurred a copy operation,

even if the file data was cached

• Linux 2.4 introduced zero-copy Sendfile• Windows NT pioneered zero-copy file sending with TransmitFile, the

Sendfile equivalent, in Windows NT 4

File DataBuffer

Network AdapterBuffer

Network

File DataBuffer

NetworkDriver

NetworkNetworkDriver

1-Copy 0-Copy

Page 396: Operating Systems User Interfaces

396

Wake-one Socket Semantics• Linux 2.2 kernel had the thundering herd or

overscheduling problem– In a network server application there are typically several

threads waiting for a new connection– In v2.2 when a new connection came in all the waiters would

race to get it• Ingo Molnar’s response:

– 5/2/99: “here he again forgets to _prove_ that overscheduling happens in Linux.”

– 5/7/99: “as of 2.3.1 my wake-one implementation and waitqueues rewrite went in”

• In Linux 2.4 only one thread wakes up to claim the new connection

• Windows NT has always had wake-1 semantics

Page 397: Operating Systems User Interfaces

397

Asynchronous I/O

• Linux 2.2 only supported asynchronous I/O on socket connect operations and tty’s

• Linux 2.6 adds asynchronous I/O for direct-disk access– AIO model includes efficient management of asynchronous I/O

• Also added alternate epoll model– Useful for database servers managing their database on a

dedicated raw partition– Database servers that manage a file-based database suffer from

synchronous I/O• Windows I/O is inherently asynchronous• Windows has had completion ports since NT 3.5

– More advanced form of AIO

Page 398: Operating Systems User Interfaces

398

Light-Weight Synchronization• Linux 2.6 introduces Futexes– There’s only a transition to kernel-mode when

there’s contention• Windows has always had CriticalSections– Same behavior

• Futexes go further:– Allow for prioritization of waits– Works interprocess as well

Page 399: Operating Systems User Interfaces

399

A Look at the Future

• The kernel architectures are fundamentally similar– There are differences in the details– Linux implementation is adopting more of the good ideas used in

Windows• For the next 2-4 years Windows has and will maintain an

edge– Linux is still behind on the cutting edge of performance tricks– Large performance team and lab at Microsoft has direct ties into the

kernel developers• As time goes on the technological gap will narrow

– Open Source Development Labs (OSDL) will feed performance test results to the kernel team

– IBM and other vendors have Linux technology centers– Squeezing performance out of the OS gets much harder as the OS

gets more tuned

Page 400: Operating Systems User Interfaces

400

Linux Technology Unknowns• Linux kernel forking

– RedHat has already done it: Red Hat Enterprise Server v3.0 is Linux 2.4 with some Linux 2.6 features

• Backward compatibility philosophy– Linus Torvalds makes decisions on kernel APIs and architecture based

on technical reasons, not business reasons

Page 401: Operating Systems User Interfaces

¿Qué es Mac OS X?

• Mac OS X es el actual sistema operativo de la familia de ordenadores Macintosh.

• Es un sistema operativo basado en UNIX.

• Contiene un núcleo de bajo nivel que se llama Darwin y esta basado en la licencia APSL (Apple Public Source License).

• Incorpora 3 tecnologías: – Quartz Extreme – OpenGL – QuickTime

Page 402: Operating Systems User Interfaces

Capas del Sistema Mac OS X

Page 403: Operating Systems User Interfaces

Núcleo del Sistema Operativo• El núcleo se refiere a la base fundamental de Mac OS

X.• Es conocido como Darwin.• Esta capa es responsable para el manejo de todas las

operaciones de E/S (entrada y salida)• También maneja la memoria y el uso del procesador.

Page 404: Operating Systems User Interfaces

Servicios del Núcleo• Implementan los servicios del sistema

operativo, los cuales son usados por las aplicaciones.

• Entre algunos de estos servicios tenemos:– QuickTime (Reproducir Videos)– Quartz (Dibujos en 2D)– Core Audio, Video (Efectos especiales)

Page 405: Operating Systems User Interfaces

Framework para Desarrolladores• Permite la ejecución de varias aplicaciones en Mac

OS X.• Un Framework es una estructura de soporte definida,

puede incluir soporte de programas, librerías y un lenguaje común para ayudar a desarrollar y unir los diferentes componentes de un proyecto.

Page 406: Operating Systems User Interfaces

Interfáz del Usuario y Aplicaciones• Las aplicaciones son los programas que tú ejecutas.• La capa de aplicación es donde el usuario interactúa

con su Macintosh.• Además de las aplicaciones diseñadas para Apple,

Mac OS X incluye soporte para ejecutar aplicaciones basadas en: Java, UNIX y aplicaciones clásicas del sistema Mac OS 9.

Page 407: Operating Systems User Interfaces

Evolución del Sistema Mac OS X

• Las diferentes versiones de Mac OS X van apodadas con los nombres de grandes felinos en inglés:

– Mac OS X Cheeta v10.0 - Marzo 2001– Mac OS X Puma v10.1 - Septiembre 2001– Mac OS X Jaguar v10.2 - Agosto 2002– Mac OS X Panther v10.3 - Octubre 2003– Mac OS X Tiger v10.4 - Abril 2005

• Próximamente se lanzará oficialmente el nuevo Mac OS X Leopard en su versión 10.5

Page 408: Operating Systems User Interfaces

Requerimientos Mínimos para instalar Mac OS X Tiger

• Ordenador Macintosh con procesador PowerPC G3, G4, G5 o procesador Intel.

• FireWire incorporado• Lector de DVD• 256 MB de RAM• Tarjeta de video integrada y

compatible con Apple.• 3 GB de espacio disponible en

disco (4 GB si deseas instalar las herramientas de desarrollo)

Page 409: Operating Systems User Interfaces

Preparandose para la instalación

• Es muy importante tomar las precauciones necesarias antes de instalar Mac OS X.– Respaldar información importante– Leer el documento “Leame antes de Instalar”– Recolectar información de tu computador– Actualizar el Firmware.– Si se requiere utilizar las aplicaciones clásicas

de Mac OS 9, es necesario primeramente actualizar a la versión 9.2.2 y luego instalar el sistema base Mac OS X.

Page 410: Operating Systems User Interfaces

Eligiendo un Método de Partición

• El particionamiento divide un disco en secciones o volúmenes.

• Es necesario borrar toda la información en el disco para realizar el particionamiento.

• Existen 2 tipos de configuraciones en las que se puede instalar Mac OS X:

Page 411: Operating Systems User Interfaces

Eligiendo el tipo de Instalación• Además del tipo de instalación por defecto existe otros tipos de

instalación:– Actualización– Archivar e Instalar– Borrar e Instalar

Page 412: Operating Systems User Interfaces

Completando la Instalación

• Cuando la instalación se ha completado, el instalador reinicia el equipo y se inicia el Asistente de Instalación, el cuál recolecta información necesaria para registrar Mac OS X y crear una nueva cuenta de usuario.

• La cuenta inicial que se crea al instalar Mac OS X, es una cuenta de administrador, la cual permite cambiar las configuraciones del sistema e instalar aplicaciones y utilidades.

Page 413: Operating Systems User Interfaces

Solucionando problemas de instalación• Existen 3 fases críticas en las que pueden

considerar posibles puntos de fallo:– Leer paquetes de DVD de instalación de Mac OS X– Problemas al procesar los paquetes desde la

memoria RAM– Problemas escribiendo los paquetes en el Volumen

de destino.

Page 414: Operating Systems User Interfaces

Tips para la Solución de problemas• Asegúrate que el equipo cumple con los

requerimientos mínimos para la instalación, incluyendo la versión del Firmware.

• Revisar los Logs de instalación (Archivo > Mostrar Logs)

• Reiniciar el equipo en caso de que se esté efectuando alguna actualización.

• Desconectar cualquier dispositivo que pueda afectar el proceso de instalación, únicamente se necesita un teclado, mouse y un monitor.

• Remover memoria RAM que no sea Apple.

Page 415: Operating Systems User Interfaces

Cuentas de Usuario• 3 tipos de usuarios:

– Estándar– Administrador– Administrador del Sistema (Super Usuario, root)

• Pueden existir muchas cuentas de usuario Estándar y Administrador, pero en Mac OS X existe 1 usuario Administrador del Sistema.

• Un usuario contiene los siguientes atributos:

• Nombre Completo

• Nombre corto (username)

• UID (User ID)

• Carpeta Personal (Home Folder)

Page 416: Operating Systems User Interfaces

Creando y Editando Cuentas de Usuario

Preferencias del Sistema

Page 417: Operating Systems User Interfaces

Utilizando el Cambio rápido de usuarios

Page 418: Operating Systems User Interfaces

Asegurando tu Mac• Mac OS X posee características de seguridad

robustas, gracias a su sistema basado en UNIX.• Existen varios tipos de contraseñas (passwords) que

utiliza Mac OS X.– Login Password. (Usuarios)– Open Firmware Password (Asegurar el proceso de inicio).– Master Password. (File Vault, Recuperar datos encriptados)– Resource Passwords (Mail, carpetas comprimidas,

encriptación, Sitios Web).– Keychain Password (Base de datos de Claves).

Page 419: Operating Systems User Interfaces

Asegurando tu cuenta con FileVault

• FileVault habilita al usuario para encriptar su carpeta personal.

• Toda la carpeta personal se transfiere a una imagen de disco encriptada ajustable.

• Cuando el usuario inicia la sesión, la imagen se monta y se desencripta.

• En casos de olvidar la contraseña se de debe crear una “Contraseña Maestra”

Page 420: Operating Systems User Interfaces

Otras opciones de Seguridad

• Solicitar una contraseña cuando la computadora está en reposo.

• Deshabilitar el inicio de sesión automático.

• Preguntar siempre por una contraseña en las preferencias del sistema.

• Cerrar la sesión después de un determinado tiempo.

Page 421: Operating Systems User Interfaces

Revisión

Page 422: Operating Systems User Interfaces

Questions?