C - 具有多个进程的内存映射

时间:2015-04-28 05:18:47

标签: c memory mapping mmap

我有一项任务要求我编写一个多处理程序,该程序使用包含字符串的内存映射文件。父进程将文件映射到内存后,它会生成2个子进程来修改该文件。子1输出文件的内容,将文件的内容转换为大写的等价物,然后输出文件的新内容。孩子2等待1秒让孩子1完成,输出文件的内容,删除任何连字符" - "字符,然后输出文件的新内容。我的两个子进程的问题在于,在首次显示文件的内容之后,进程尝试修改文件的内容,但是两个子进程都不输出文件的新内容。我在运行或编译时没有错误,所以我无法找出问题所在。当然,我是记忆映射的新手,所以请随时让我知道我做错了什么。这是我的源代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <string.h>

int main (int argc, char *argv[]) { 
    struct stat buf;
    int fd, length, status, i, j, k;
    char *mm_file;
    char *string = "this is a lowercase-sentence.";
    length = strlen(string);

    fd = open(argv[1], O_CREAT | O_RDWR, 0666); //Creates file with name given at command line
    write(fd, string, strlen(string)); //Writes the string to be modified to the file
    fstat(fd, &buf); //used to determine the size of the file

    //Establishes the mapping
    if ((mm_file = mmap(0, (size_t) buf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == (caddr_t) - 1) {
       fprintf(stderr, "mmap call fails\n");
    }

    //Initializes child processes
    pid_t MC0;
    pid_t MC1;

    //Creates series of child processes which share the same parent ID
    if((MC0 = fork()) == 0) {
        printf("Child 1 %d reads: \n %s\n", getpid(), mm_file);
        //{convert file content to uppercase string};
        for (i = 0; i < length; i++) {
            string[i] = toupper(string[i]);
        }
        //sync the new contents to the file
        msync(0, (size_t) buf.st_size, MS_SYNC);
        printf("Child 1 %d reads again: \n %s\n", getpid(), mm_file);
        exit(EXIT_SUCCESS); //Exits process
    } else if ((MC1 = fork()) == 0) {
        sleep(1); //so that child 2 will perform its task after child 1 finishes
        ("Child 2 %d reads: \n %s\n", getpid(), mm_file);
        //{remove hyphens}
        for (j = 0; j < length; i++) {
            if (string[i] == '-') {
                string[i] = ' ';
            }
        }
        //sync the new contents to the file
        msync(0, (size_t) buf.st_size, MS_SYNC);
        printf("Child 2 %d reads again: \n %s\n", getpid(), mm_file);
        exit(EXIT_SUCCESS); //Exits process
   } 

   // Waits for all child processes to finish before continuing.
   waitpid(MC0, &status, 0);
   waitpid(MC1, &status, 0);

   return 0;
}

然后我的输出如下:

**virtual-machine:~$** ./testt file

Child 1 3404 reads: 

this is a lowercase-sentence.

Child 2 3405 reads: 

this is a lowercase-sentence.

All child processes have finished. Now exiting program.

**virtual-machine:~$**

但我希望的结果是:

**virtual-machine:~$** ./testt file

Child 1 3404 reads: 

this is a lowercase-sentence.

Child 1 3404 reads again: 

THIS IS A LOWERCASE-SENTENCE.

Child 2 3405 reads: 

THIS IS A LOWERCASE-SENTENCE.

Child 2 3405 reads: 

THIS IS A LOWERCASE SENTENCE.

All child processes have finished. Now exiting program.

**virtual-machine:~$**

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这里有一些错误。首先,您写入文件,然后将其映射到内存中。映射是正确的,但写不是。如果字符串具有 n 个字符,则必须写入 n + 1 个字符,因为C中的字符串以空值终止。现在你只有 n ,所以所有C字符串函数都会尝试至少再访问一个字节,这是不好的。如果那个额外的字节不为空(零),那么函数将更进一步。在调试中,它们可能会被归零,但在优化的代码中通常不会。所以你必须使用

write(fd, string, strlen(string)+1); //Writes the string to be modified to the file

然后你这样做:

    for (i = 0; i < length; i++) {
        string[i] = toupper(string[i]);
    }

这只会更改指针string引用的数据,这与内存映射文件无关。你应该:

    for (i = 0; i < length; i++) {
        mm_file[i] = toupper(mm_file[i]);
    }

第二个子进程也是如此。

你的msync()电话也有点怀疑。您将内存地址设置为0,这不在内存映射文件中,因此它不会同步内容。您需要致电msync(mm_file, (size_t) buf.st_size, MS_SYNC);

此外,许多编译器会将常量字符串放入只读内存中,因此甚至不允许您更改string引用的数据。在这种情况下,似乎你被允许。

还要记住,文件的长度比字符串的长度大一个字节,因此请正确使用变量。目前,您可以使用文件长度同步文件,并使用字符串长度处理字符串。

答案 1 :(得分:0)

你让mem map妨碍逻辑。

要让这个工作注释掉所有mem map的东西,只需处理文件。 这将告诉您,两个孩子都不会从输入文件中读取内容,更不用说将新内容写入其中。 在某些操作系统下,如果你要混合读写,那么Linux就是其中之一,你需要在它们之间进行搜索以保持写和指针位于同一位置。这可能必须是fseek(stream,0,SEEK_CUR);

孩子一应该是

// Lock file here
rewind(file);
printf ("child 1 reads ");
int ch;
while(1){
   ch = fgetc(file);
  if(ch == EOF) break;
  fputc (Ch,stdout );
}
 fputc('\n',stdout );

Rewind(file);
while(1){
  ch=fgetc (file);
  if(Ch == EOF) break;
  fseek(file,-1,SEEK_CUR);
  fputc (toupper (Ch),file);
  fseek(file,0,SEEK_CUR);
}

Rewind ( file);
Printf (" child 1 reads ");
while(1){
  ch=fgetc(file);
  if(Ch == EOF) break;
  fputc (Ch,file) ;
}

// Unlock file here

因为有多个进程作用于同一个对象,所以必须实现写锁定(独占锁)。 阅读手册flock(2),fcntl(2)和lockf(3)。

这些协作锁可以实现为信号量。 在没有锁定的情况下,两个孩子可能会尝试同时写入同一个字符,在这个例子中,因为一个孩子使用连字符和其他字母而无所谓。

现在它正在取消注释你的mem地图。