[英]mmap error on linux (using somethingelse)
确实,我认为我已经完成了我的项目,直到由于mmap()
而在ubuntu上不接受编译为止。 我正在尝试使用fork()
访问(读取)文件。 没关系。 但是,当我想计算已读文件的数量,输入的文件夹(目录)和子目录时,我感到很遗憾! 我如何以及如何使用或更改mmap()
因为error: 'MAP_ANON' undeclared (first use in this function)|
。 在Mac上,这很好,但是在ubuntu错误上。 感谢您的帮助。
#define _XOPEN_SOURCE 700
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <ftw.h>
#include <ctype.h>
#include <sys/mman.h>
#define MAX_PATH_LEN 2048
static int *wordCount = 0;
static int *childCount = 0;
static int *folderCount = 0;
int relatedWord(const char *arr);
int checkWord(const char arr[], int size);
void err_sys(const char *msg);
int disp(const char *filepath, const struct stat *finfo, int flag, struct FTW *ftw);
int main(int argc, char *argv[])
{
//struct stat finfo;
//int count = 0;
wordCount = mmap(NULL, sizeof *wordCount, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON, -1, 0);
childCount = mmap(NULL, sizeof *childCount, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON, -1, 0);
folderCount = mmap(NULL, sizeof *folderCount, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON, -1, 0);
if (argc != 2) {
fprintf(stderr, "Wrong number of arguments!\nUsage: dirwalk6 <path>\n");
exit(EXIT_FAILURE);
}
if (nftw(argv[1], disp, 20, 0) < 0)
err_sys("ntfw");
printf( "\nTotal words = %d\n\n", *wordCount);
printf( "\nTotal folders = %d\n\n", *folderCount);
printf( "\nTotal childs = %d\n\n", *childCount);
return 0;
}
int disp(const char *filepath, const struct stat *finfo, int flag, struct FTW *ftw)
{
int count = 0; /* number of words */
switch (flag) {
case FTW_F: /* determining file */
printf("%*s%s\n", ftw->level * 4, "", filepath);
pid_t pid;
pid=fork();
if(pid < 0)
{
perror("Error corresponding to fork()");
}
else if (pid == 0)
{
count += relatedWord(filepath);
*wordCount += count;
*childCount += 1;
exit(1);
}
else
{
while( pid != wait(0) ) ;
}
// printf( "word = %d, file = %s \n", count,filepath);
break;
case FTW_D: /* determining folder */
printf("%*s%s\n", ftw->level * 4, "", filepath + ftw->base);
*folderCount += 1;
break;
}
return 0;
}
从mmap(2)
的手册页中(我的粗体):
仅当定义了
_BSD_SOURCE
或_SVID_SOURCE
才定义某些标志常量。 (也需要_GNU_SOURCE
,并且由于该标志都是Linux特定的,因此要求该宏更加逻辑化。)相关标志为:MAP_32BIT
,MAP_ANONYMOUS
( 和同义词MAP_ANON
),MAP_DENYWRITE
,MAP_EXECUTABLE
,MAP_FILE
,MAP_GROWSDOWN
,MAP_HUGETLB
,MAP_LOCKED
,MAP_NONBLOCK
,MAP_NORESERVE
,MAP_POPULATE
和MAP_STACK
。
因此,您需要在文件顶部定义_BSD_SOURCE
, _SVID_SOURCE
或(如果我没看错的话) _GNU_SOURCE
,但是无论如何要在
#include <sys/mman.h>
根据@mafso的评论,最好在包含任何系统头之前进行此操作(尤其是在另一个头本身包含<sys/mman.h>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.