Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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); }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote