我正在用 C 撰寫一個程式,并使用 mmap() 使行程將計算回傳到它們的主行程。
這是代碼:
int *results = mmap ( NULL, count*sizeof(int),
PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 );
for (i = 0; i < count; i )
{
pid_t pid = fork();
if (pid == 0)
{
/// some calculations in the child.
}
// I save the result to ith element of mmap
results[i] = calculation;
}
else{
wait(NULL);
}
}
// The following part arises an error called segmentation fault.
for (i = 0; i < count; i )
{
printf(" results[%d] = %d.\n", i, results[i]);
}
當我嘗試訪問結果時,出現錯誤。我該如何解決?
任何幫助表示贊賞。
uj5u.com熱心網友回復:
參考man mmap:
MAP_ANONYMOUS
映射不受任何檔案的支持;它的內容被初始化為零。fd 引數被忽略;但是,如果指定了 MAP_ANONYMOUS(或 MAP_ANON),某些實作要求 fd 為 -1,并且便攜式應用程式應確保這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355205.html
下一篇:如何繞過零大小的陣列?
