[英]Why doesn't array work by using fork() function?
我試圖解決這個問題。
問題是
我應該創建一個創建子進程的進程。
子進程應將1到10寫入int數組大小10 {初始值0}。
媽媽的過程應該等到孩子寫完為止。 子進程完成后,母進程將打印出數組(例如1,2,...,10),並將其全部替換為-1,然后再打印一次。
兒童是生產者,母親是消費者。 (只有一個孩子,只有一個消費者。他們只能這樣做一次。)
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
int main(){
int arr[10]={0,};
pid_t pid;
int state;
pid = fork();
if(pid == -1) // error
{
printf("can't fork, error\n");
exit(-1);
}
else if (pid == 0) // Child ( producer )
{
printf("\nProducer is created.\n");
printf("array: ");
for(c=0; c<10; c++)
{
printf("%d ", arr[c]);
arr[c]=c+1;
}
}
else // Mother ( consumer )
{
pid=wait(&state);
sleep(1);
printf("\nConsumer takes control of array");
printf("\narray:");
for(j=0;j<10;j++)
{
printf(" %d", arr[j]);
}
printf("\nConsumer is done.");
printf("\narray: ");
for ( i =0; i<10; i++)
{
arr[i]=-1;
printf("%d ", arr[i]);
}
printf("\ndone\n");
exit(0);
}
return 0;}
我想要輸出
0 0 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 9 10
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
但
我的輸出是
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
我的代碼有什么問題?
進程的內存地址空間將“在寫入時復制”。 因此,兩個進程之間不共享該數組。
如果要在不同進程(例如父級和子級)之間共享大量數據,則有多種方法。 最常見的三個是
shm*
API提供 mmap
API提供 建議:閱讀已故的W. Richard Stevens可以找到的所有內容,例如Unix Environment中的Programming 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.