sparse-tools/src/test_mmap.c

71 lines
1.4 KiB
C

//
// Created by haraldwolff on 15.08.22.
//
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[]){
long size;
argv++;
struct stat stat;
while (*argv){
fprintf(stdout, "Testing to map %s\n", *argv);
fflush(stdout);
int f = open(*argv, O_RDWR | O_DIRECT);
if (f<0)
{
fprintf(stderr, "could not open %s. %s\n", *argv, strerror(errno));
fflush(stderr);
} else {
if (fstat(f, &stat)){
fprintf(stderr, "could not stat %s. %s\n", *argv, strerror(errno));
fflush(stderr);
} else {
if ((stat.st_mode & S_IFMT)==S_IFBLK){
fprintf(stdout,"is a block device.\n");
long offset = lseek(f, 0, SEEK_END);
fprintf(stdout, "device size seems to be: %ld\n\n", offset);
size = offset;
} else {
fprintf(stdout,"size: %d bytes.\n\n", stat.st_size);
size = stat.st_size;
}
fflush(stdout);
void *mapping = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, f, 0);
if (mapping == MAP_FAILED){
fprintf(stderr, "could not mmap %s. %s\n", *argv, strerror(errno));
fflush(stderr);
} else {
fprintf(stdout, "successfully mapped %s to memory.\n\n\n", *argv);
munmap(mapping, 8192);
}
}
close(f);
}
argv++;
}
return 0;
}