Description
You have two sample files attached to this assignment: one showing how to work with memory sharing and another showing implementing a copy program using open(), read(), and write() methods. Your job here is to convert the copy program to copy one file to another file(with a different name) using memory mapping APIs, not using read() methods. You can use write API.
Copy.c
#define NULL 0
#define BUFFSIZE 512
#define PMODE 0644 /* RW for owner, R for group, others */
main ( int argc, char *argv[])
{
int f1, f2, f3;
char buf[BUFFSIZE];
if(argc != 3)
error(“Usage: copy from to”, NULL);
if(( f1 = open(argv[1], 0)) == -1)
error(“copy can’t open %s”, argv[1]);
if(( f2 = create(argv[2], PMODE)) == -1)
error(“copy: can’t create %s”, argv[2]);
while (( f3 = read(f1, buf, BUFFSIZE)) >0)
if(write (f2, buf, n) != n)
error(“copy: write error”, NULL);
exit(0);
}
void error( char *s1, char *s2)
{
printf(s1, s2);
printf(“n”);
exit(1);
}
MappingSample.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
int main(int argc, char *argv[])
{
struct stat sb;
off_t len;
char *p;
int fd;
if(argc < 2){
fprintf(stderr, “usage: %s <file>n”, argv[0]);
return 1;
}
fd = open(argv[1], O_RDONLY);
if(fd == -1){
perror(“open”);
return 1;
}
if(fstat(fd, &sb) == -1){
perror(“fstat”);
return 1;
}
if(!S_ISREG(sb.st_mode)){
fprintf(stderr, “%s is not a filen”, argv[1]);
return 1;
}
p = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if(p == MAP_FAILED){
perror(“mmap”);
return 1;
}
for(len = 0; len < sb.st_size; len++){
putchar(p[len]);
}
if(munmap(p, sb.st_size) == -1) {
perror(“munmap”);
return 1;
}
if(close(fd) == -1) {
perror(“close”);
return 1;
}
return 0;
}