Question: Instruction Write a program to create a mmap() that is shared by multiple threads. Use fstat() to obtain the size of the mapped file to
Instruction
Write a program to create a mmap() that is shared by multiple threads. Use fstat() to obtain the size of the mapped file to size the mapping. Find out the number of logical processors (or cores) available programmatically by calling sysconf(), as shown, and display this number.
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
For this exercise, however, you are going to create four (4) threads only. Every thread should see the mapping. Each thread will display separate partial contents (sb.st_size/4 bytes) of the file.
Finally, unmap and close the file.
Source Code (help us fix if there are error, it RUNS, but does it satisfy the instructions' requirements?):
#include
int main (int argc, char * argv[]) { char *addr; int fd; struct stat sb;
if (argc != 2 || strcmp(argv[1], "help") == 0) { printf("Usage: %s file ", argv[0]); }
fd = open(argv[1], O_RDONLY); if (fd == -1) { printf("File open failed. "); exit(EXIT_FAILURE); }
/* Obtain size of the file and use it to specify the size of the buffer to be written. */
if (fstat(fd, &sb) == -1) { printf("fstat error "); exit(EXIT_FAILURE); }
addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (addr == MAP_FAILED) { printf("mmap failed "); exit (EXIT_FAILURE); }
if (write(STDOUT_FILENO, addr, sb.st_size) != sb.st_size) { // Delete the mapping. if (munmap(addr, sb.st_size) == -1){ printf("munmap failed "); exit(EXIT_FAILURE); } // Close the file close(fd); }
exit(EXIT_SUCCESS); }
Note: If you are planning to write this on paper, please write in printed English, prefer typed on keyboard.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
