mmap,msync和linux进程终止

mmap,msync和linux进程终止,第1张

mmap,msync和linux进程终止

我决定不那么懒惰,并通过编写一些代码来回答是否将数据最终写入磁盘的问题。答案是它将被编写。

这是一个程序,将一些数据写入mmap文件后会突然杀死自己:

#include <stdint.h>#include <string.h>#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <unistd.h>#include <sys/types.h>#include <sys/mman.h>#include <sys/stat.h>#include <fcntl.h>typedef struct {  char data[100];  uint16_t count;} state_data;const char *test_data = "test";int main(int argc, const char *argv[]) {  int fd = open("test.mm", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0700);  if (fd < 0) {    perror("Unable to open file 'test.mm'");    exit(1);  }  size_t data_length = sizeof(state_data);  if (ftruncate(fd, data_length) < 0) {    perror("Unable to truncate file 'test.mm'");    exit(1);  }  state_data *data = (state_data *)mmap(NULL, data_length, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, fd, 0);  if (MAP_FAILED == data) {    perror("Unable to mmap file 'test.mm'");    close(fd);    exit(1);  }  memset(data, 0, data_length);  for (data->count = 0; data->count < 5; ++data->count) {    data->data[data->count] = test_data[data->count];  }  kill(getpid(), 9);}

这是一个在上一个程序失效后验证结果文件的程序:

#include <stdint.h>#include <string.h>#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <unistd.h>#include <sys/types.h>#include <sys/mman.h>#include <sys/stat.h>#include <fcntl.h>#include <assert.h>typedef struct {  char data[100];  uint16_t count;} state_data;const char *test_data = "test";int main(int argc, const char *argv[]) {  int fd = open("test.mm", O_RDONLY);  if (fd < 0) {    perror("Unable to open file 'test.mm'");    exit(1);  }  size_t data_length = sizeof(state_data);  state_data *data = (state_data *)mmap(NULL, data_length, PROT_READ, MAP_SHARED|MAP_POPULATE, fd, 0);  if (MAP_FAILED == data) {    perror("Unable to mmap file 'test.mm'");    close(fd);    exit(1);  }  assert(5 == data->count);  unsigned index;  for (index = 0; index < 4; ++index) {    assert(test_data[index] == data->data[index]);  }  printf("Validatedn");}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5024684.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存