Write a program, analogous to the Unix/Linux cat command, that uses mmap() and w
ID: 3856739 • Letter: W
Question
Write a program, analogous to the Unix/Linux cat command, that uses mmap() and write() system calls (instead of read() or write() ) to copy a source file to the screen. Use fstat() to obtain the size of the input file which can be used to size the required memory mapping.
The statement to write the file contents to STDOUT is
write (STDOUT_FILENO, addr, sb.st_size);
where
addr is the start of the mapping, gotten from mmap() and,
sb.st_size is the size of the mapping returned by fstat() in the
sb struct.
Please show the command line to compile the file and run the code and the screenshots
Explanation / Answer
int main(int argc, char *argv[]) { int fd; char *addr; struct stat sb; if (argc != 2 || strcmp(argv[1], "--help") == 0) usageErr("%s shm-name ", argv[0]); fd = shm_open(argv[1], O_RDONLY, 0); /* Open existing object */ if (fd == -1) errExit("shm_open"); /* Use shared memory object size as length argument for mmap() and as number of bytes to write() */ if (fstat(fd, &sb) == -1) errExit("fstat"); addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) errExit("mmap"); if (close(fd) == -1) /* 'fd' is no longer needed */ errExit("close"); write(STDOUT_FILENO, addr, sb.st_size); printf(" "); exit(EXIT_SUCCESS); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.