我有一項任務,要求我編寫一個多處理程序,該程序可與包含字符串的內存映射文件一起使用。父進程將文件映射到內存後,它會生成2個子進程來修改該文件。子1輸出文件的內容,將文件的內容轉換爲大寫字母,然後輸出文件的新內容。孩子2等待1秒讓孩子1完成,輸出文件的內容,刪除任何連字符「 - 」字符,然後輸出文件的新內容。我的兩個子進程的問題是,在第一次顯示文件的內容之後,進程嘗試修改文件的內容,但子進程都不輸出文件的新內容。在運行或編譯時我沒有遇到任何錯誤,所以我無法找出問題所在。當然,我是內存映射的新手,所以請隨時讓我知道我做錯了什麼。下面是我的源代碼:C - 使用多個進程的內存映射
#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:~$**
任何幫助是極大的讚賞。
因爲您從不編輯內存映射文件。你只需要改變'string'變量,這是完全不同的。 –
我的導師給了我一些我們程序中需要的代碼片段。我認爲msync函數是將字符串變量重新映射到內存的東西。我是否錯誤地使用了功能,或者我只是不理解它的使用? – Anthony
'msync()'會同步內存映射的文件內容。您設置爲所需原始字符串的'string'變量,並且它始終指向那裏。您只需將其內容複製到文件中,但指針不會更改爲指向內存映射區域。 –