确实,我认为我完成了我的项目,直到编译因为mmap()
而未在ubuntu上接受。我尝试使用fork()
访问(读取)文件。它很好。但是,当我想要计算读取文件的数量,输入文件夹(目录)和孩子时,我发了!如何以及我可以使用或更改mmap()
,因为我得到error: ‘MAP_ANON’ undeclared (first use in this function)|
。在Mac上,它是okey但是在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;
}
答案 0 :(得分:1)
来自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>