Background
When using shared memory on Linux, the most common way is to use MMAP mapping file: a few days ago, when writing a program, there was an error in the execution of MMAP:
./test_mmap tmp.txt
mmap: Invalid argument
The procedure is as follows:
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd;
struct stat sb;
char *mmapped;
if (argc != 2) {
return -1;
}
fd = open(argv[1], O_RDWR);
if(fd < 0) {
perror("open");
return -1;
}
if(fstat(fd, &sb) == -1) {
perror("fstat");
return -1;
}
mmapped = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mmapped == MAP_FAILED) {
perror("mmap");
return -1;
}
close(fd);
mmapped[0] = '1';
if(msync((void*)mmapped, sb.st_size, MS_SYNC) == -1) {
perror("msync");
return -1;
}
munmap((void *)mmapped, sb.st_size);
return 0;
}
I have encountered this problem before, but I forgot what happened and took a little time to find the reason. In order to avoid repeating the mistakes, write an article and record it.
reason
On my environment, the reason for this error is that the mmap mapped file is not on the local machine! My Ubuntu is in a virtual machine, and the host is macOS. A folder on the host is shared to the virtual machine, and it is in this shared folder that the mmap file is in when I execute the program, so this strange error is reported.
Read More:
- [Solved] Ubuntu16.4Install vcs2016 Error: mount.vboxsf: mounting failed with the error: Invalid argument
- [Solved] Samba Mount Error: mount error(22): Invalid argument
- Solution to gzip: stdin: invalid compressed data — format violated error in decompressing. Tgz file under Linux
- [Solved] Linux — 9 — txt files are copied from windows to Linux and read error
- [Solved] Linux Error: mipsel-linux-gcc: fatal error: no input files
- ERROR: Invalid subnet : invalid CIDR address: [How to Fix]
- Linux: How to Fix undefined reference to `itoa’
- How to Create Threads in Linux
- Easycvr package Linux version error net_DVR_DownFileByName_Stop
- [Solved] Error in installing backups.lzma for Python on Linux
- Linux accesses the shared directory of windows, pysmb (parameter remote)_Name (defined)
- [Solved] Linux scp Error: Host key verification failed.
- Linux Error: audit: backlog limit exceeded [How to Solve]
- [Solved] Linux VI Error: Can‘t open file for writing
- Linux Connect Error: network.service failed [How to Solve]
- Linux Traceroute Command Examples
- Linux: How to Solve Rabbitmq Plug-in Install Error
- Kylin arm64 linux configure: error: cannot guess build type; you must specify one
- Linux First Install oracle Start Error [How to Solve]
- Installation and configuration of redis in Linux