06 aprilie 2011

Exemplu de folosire memorie virtuala

Implementarea comenzii cp din Linux, folosind mmap :

int main (int argc, char *argv[])
{
int fdin, fdout, rc;
char *src, *dst;
struct stat statbuf;

DIE(argc != 3, "Usage: ./mycp ");

/* Open input and output files */
fdin = open (argv[1], O_RDONLY);
DIE(fdin == -1, "open fdin");

/* Open/create the output file */
fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644);
DIE(fdout == -1, "open fdout");

/* truncate the output file to the input file size */
rc = fstat(fdin, &statbuf);
DIE(rc == -1, "fstat");
double size = (double)statbuf.st_size;
rc = ftruncate(fdout, size);
DIE(rc == -1, "ftruncate");

/* mmap the input and output file */
src = mmap (0, size, PROT_READ, MAP_SHARED, fdin, 0);
DIE( rc==-1, "mmap");
dst = mmap (0, size, PROT_WRITE, MAP_SHARED, fdout, 0); // la MAP_PRIVATE , rezultatul ramane doar in memorie
DIE( rc==-1, "mmap");

/* copy the input file to the output file */
memcpy(dst, src, size);

/* clean up */
rc = munmap(src, size);
DIE(rc == -1, "munmap");
rc = munmap(dst, size);
DIE(rc == -1, "munmap");

/* Close files */
rc = close(fdin);
DIE(rc == -1, "close source");

rc = close(fdout);
DIE(rc == -1, "close destination");

return 0;
}

Niciun comentariu: