栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

mmap,msync和linux进程终止

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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");}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/412271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号