我正在try 写入和读取使用shm_open
打开的文件描述符.它可以在Linux上运行,但不能在MacOS(特别是MacOS蒙特雷12.5 21G72)上运行.
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(int argc, const char * argv[]) {
int fd = shm_open("/example", O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
if (fd < 0) {
printf("shm_open() failed %s (%d)\n", strerror(errno), errno);
return 1;
}
const char *buf = "hello world";
unsigned long len = strlen(buf);
ssize_t ret = write(fd, buf, len);
if (ret < 0) {
printf("write() failed %s (%d)\n", strerror(errno), errno);
return 1;
}
ret = lseek(fd, 0, SEEK_SET);
if (ret < 0) {
printf("lseek() failed %s (%d)\n", strerror(errno), errno);
return 1;
}
char *newbuf = calloc(len + 1, 1);
ret = read(fd, newbuf, len);
if (ret < 0) {
printf("read() failed %s (%d)\n", strerror(errno), errno);
return 1;
}
printf("read: %s\n", newbuf);
return 0;
}
在Linux上,输出如我所料:
$ cc main.c
$ ./a.out
read: hello world
在MacOS上,我得到的信息是:
$ cc main.c
$ ./a.out
write() failed Device not configured (6)