PDF de programación - Bloque I: Principios de sistemas operativos

Imágen de pdf Bloque I: Principios de sistemas operativos

Bloque I: Principios de sistemas operativosgráfica de visualizaciones

Publicado el 14 de Enero del 2017
487 visualizaciones desde el 14 de Enero del 2017
140,6 KB
22 paginas
Creado hace 13a (21/02/2011)
UNIVERSIDAD
DE CANTABRIA

Bloque I: Principios de sistemas
operativos
Tema 1. Principios básicos de los sistemas operativos
Tema 2. Concurrencia
Tema 3. Ficheros
Tema 4. Sincronización y programación dirigida por eventos
Tema 5. Planificación y despacho
Tema 6. Sistemas de tiempo real y sistemas empotrados
Tema 7. Gestión de memoria
Tema 8. Gestión de dispositivos de entrada-salida

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS
3

© Michael González, J. Javier Gutiérrez

21/feb/11

1

Notas:

UNIVERSIDAD
DE CANTABRIA

Tema 3. Ficheros

• Conceptos básicos.
• Gestión de ficheros.
• Lectura y escritura.
• Entrada/salida asíncrona.
• Entrada/salida sincronizada.
• Acceso al estado y características de ficheros.
• Funciones de gestión de directorios.
• Tuberías y ficheros especiales FIFO.

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

2

1. Conceptos básicos
El sistema de ficheros es una colección de ficheros junto a ciertos
atributos que los caracterizan
Proporciona un espacio de nombres, y contiene:

UNIVERSIDAD
DE CANTABRIA

ficheros normales: residen en memoria secundaria

-
- directorios
- dispositivos orientados al carácter
- dispositivos orientados a bloque
-

tuberías o ficheros especiales FIFO

Se puede hacer I/O sobre todos ellos, excepto los directorios
Si el sistema de ficheros no existe, el espacio de nombres (sin
directorios) y los dispositivos se mantienen

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

3

Conceptos básicos (cont.)
Descriptor de fichero (fd)
• es un entero positivo que identifica un fichero que ha sido

UNIVERSIDAD
DE CANTABRIA

abierto para I/O

• los descriptores 0, 1, y 2 suelen ser respectivamente la entrada

estándar, la salida estándar, y la salida de error

Descripción de fichero
• es una estructura de datos perteneciente al núcleo del SO y que

existe asociada a un fichero abierto

• contiene los punteros de lectura/escritura, etc.
• diferentes procesos pueden compartir una misma descripción

de fichero

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

4

Compartiendo descripciones de fichero

UNIVERSIDAD
DE CANTABRIA

Proceso Padre

fd 0
fd 1
...
fd i

Proceso Hijo

fd 0
fd 1
...
fd i

Otro Proceso

fd 0
fd 1
...
fd i

Descripciones
de ficheros

posición actual

puntero a i-nodo

posición actual

puntero a i-nodo

...

...

Tabla de
i-nodos

Información
del i-nodo

Información
del i-nodo

...

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

5

2. Gestión de ficheros
Abrir un fichero:

UNIVERSIDAD
DE CANTABRIA

#include <sys/stat.h>
#include <fcntl.h>
int open (const char *path, int oflag
[, mode_t mode]);

• abre un fichero para leer o escribir
• el path puede ser absoluto o relativo al directorio de trabajo
• crea una nueva descripción de fichero y retorna un descriptor de
fichero asociado a ella (o -1 si hay error)

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

6

Gestión de ficheros (cont.)
Las opciones definidas para oflag permiten:
• abrir para leer, escribir, o ambos

- O_RDONLY, O_WRONLY, O_RDWR
- O_APPEND

• añadir al final del fichero

• crear el fichero si no existe: requiere parámetro mode, que

UNIVERSIDAD
DE CANTABRIA

• truncar (a tamaño 0) el fichero si existe

indica los permisos de acceso
- O_CREAT
- O_TRUNC
- O_NONBLOCK

• I/O bloqueante o no bloqueante, etc.

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

7

Gestión de ficheros (cont.)
El parámetro mode se pone sólo si se crea el fichero, e indica los
permisos de lectura (R), escritura (W), y ejecución (X)
• Del propietario (USRer)
- S_IRUSR, S_IWUSR, S_IXUSR
• Del grupo de usuarios (GRouP)
- S_IRGRP, S_IWGRP, S_IXGRP
• Del resto de los usuarios (OTHers)

UNIVERSIDAD
DE CANTABRIA

- S_IROTH, S_IWOTH, S_IXOTH

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

8

Gestión de ficheros (cont.)
Crear un fichero:

UNIVERSIDAD
DE CANTABRIA

#include <sys/stat.h>
#include <fcntl.h>
int creat (const char *path, mode_t mode);

• es equivalente a un open indicando sólo escritura, creación del

fichero, y borrar la información del fichero, si existe

• esta operación sólo se puede hacer si hay sistema de ficheros

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

9

Gestión de ficheros (cont.)
Cerrar un fichero:

UNIVERSIDAD
DE CANTABRIA

#include <unistd.h>
int close (int fildes);

• destruye el descriptor de fichero
• destruye la descripción del fichero si nadie lo tiene abierto
Borrar un fichero

#include <unistd.h>
int unlink (const char *path)

• si el fichero está en uso, se borra cuando el último proceso que

lo tiene abierto lo cierra

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

10

UNIVERSIDAD
DE CANTABRIA

Gestión de ficheros (cont.)
Cambiar de nombre a un fichero

#include <stdio.h>
int rename (const char *old, const char *new)

• se puede mover el fichero a otro directorio
• se puede cambiar el nombre de un directorio
Modificar el tamaño de un fichero (truncar o expandir)

#include <unistd.h>
int ftruncate (int fildes, off_t length)

• el nuevo tamaño, en bytes, es length

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

11

Ejemplo

UNIVERSIDAD
DE CANTABRIA

// Crear un fichero con permisos de lectura y escritura para
// el propietario. Poner el tamaño a 1000 bytes y cerrarlo

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main() {

int fd;
off_t longitud=1000;

fd=creat("pepito",S_IRUSR|S_IWUSR);

if (fd==-1) {
perror("Error al crear el fichero");
exit(1);
}

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

12

Ejemplo (cont.)

UNIVERSIDAD
DE CANTABRIA

if (ftruncate(fd,longitud)==-1) {
perror("Error al cambiar el tamaño");
exit(1);
}

if (close(fd)==-1) {
perror("Error al cerrar el fichero");
exit(1);
}
exit(0);
}

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

13

Gestión de ficheros (cont.)
Posicionar el puntero de lectura/escritura

UNIVERSIDAD
DE CANTABRIA

• el nuevo puntero dependerá del valor de whence:

#include <unistd.h>
off_t lseek (int fildes, off_t offset, int whence)
- SEEK_SET: se pone igual a offset
- SEEK_CUR: se le añade offset
- SEEK_END: se pone igual al tamaño del fichero + offset

• devuelve el puntero resultante (número de bytes desde el

principio del fichero)

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

14

Gestión de ficheros (cont.)
Crear un enlace directo (link) a un fichero

UNIVERSIDAD
DE CANTABRIA

#include <unistd.h>
int link (const char *existing, const char *new)
• es una forma de dar dos nombres a un mismo fichero
• se puede hacer simbólico (el sistema almacena el nombre del

fichero destino, no una referencia a él)
#include <unistd.h>
int symlink(const char *path1, const char *path2);

Duplicar un descriptor de fichero

#include <unistd.h>
int dup (int fildes)

• retorna un descriptor referido al mismo fichero que fildes

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

15

3. Lectura y escritura
Leer:

UNIVERSIDAD
DE CANTABRIA

#include <unistd.h>
ssize_t read (int fildes, void *buf,
size_t nbyte);

• Intenta leer nbyte bytes de fichero especificado
almacenándolos en el buffer apuntado por buf
• retorna el número de bytes leidos (<=nbyte)
• la lectura puede ser bloqueante o no, según lo definido en el
open

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

16

Lectura y escritura (cont.)
Escribir:

UNIVERSIDAD
DE CANTABRIA

#include <unistd.h>
ssize_t write (int fildes, const void *buf,

size_t nbyte);

• Intenta escribir nbyte bytes del buffer apuntado por buf en el
fichero especificado por fildes
• retorna el número de bytes escritos (<nbyte si no caben)
• la escritura puede ser bloqueante o no, según lo definido en el
open

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

17

Ejemplo de lectura/escritura:
fichero “alumnos.h”

UNIVERSIDAD
DE CANTABRIA

#include <sys/types.h>

typedef struct {
char nombre[30];
char dni[10];
} alumno;

#define OK 0
#define ERROR_DE_LECTURA 1
#define ERROR_DE_ESCRITURA 2

void teclea_alumno(alumno *a);

void muestra_alumno(const alumno *a);

int escribe_alumno(const alumno *a, off_t pos, int fd);

int lee_alumno(alumno *a, off_t pos, int fd);

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

18

Ejemplo de lectura/escritura:
fichero “alumnos.c”

UNIVERSIDAD
DE CANTABRIA

#include "alumnos.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

void teclea_alumno(alumno *a) {
char tonto [80];

printf("Nombre: ");
fgets(a->nombre,30,stdin);
printf("DNI: ");
scanf("%s",a->dni);
// quitar el salto de linea
fgets(tonto,80,stdin);
}

GRUPO DE COMPUTADORES Y TIEMPO REAL
FACULTAD DE CIENCIAS

© Michael González, J. Javier Gutiérrez

21/feb/11

19

Ejemplo de lectura/escritura:
fichero “alumnos.c” (cont.)

UNIVERSIDAD
DE CANTABRIA

void muestra_alumno(const alumno *a) {
printf("Nombre: %s\n",a->nombre);
printf("DNI: %s\n\n",a->dni);
}

int escribe_alumno(const alumno *a, off_t pos, int fd) {
ssize_t escri
  • Links de descarga
http://lwp-l.com/pdf941

Comentarios de: Bloque I: Principios de sistemas operativos (0)


No hay comentarios
 

Comentar...

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad