私は、子プロセスと親プロセスの間で共有メモリを使用してプログラムを実行しようとしています。プログラムはまた、フォークを使用します。Cアクティブ待ちの子プロセス間でメモリを共有するときのエラー
運動のobjetiveがある:アクティブ待ちと -Father(共有メモリで)子供に送って3回ベクトル
を、VECを受け、それを印刷し、同期変数を変更-childここでStruct:
typedef struct{
int change[NUM_TOTAL];
int synchronize;
}Exchange;
Exchange *vec;
int fd = shm_open("/shmtest8",O_CREAT| O_RDWR,S_IRUSR|S_IWUSR);
//Check shm_open error
ftruncate(fd, 100);
vec = (Exchange*) mmap(NULL,100,PROT_READ|PROT_WRITE, MAP_SHARED, fd ,0);
x = forkFunc() //Creates a fork, and return 0 to parente and > 0 to child process
if(x == 0){ //Parent
int cont = 0;
while(cont != 3){
printf("Father\n");
vec->synchronize = 1; //Now go to to the child
while(vec->synchronize!=0); //the child change the variable to 0
cont++;
printf("cont %d",cont);
}
wait(NULL);
munmap(vec,sizeof(vec));
close(fd);
shm_unlink("/shmtest8");
}else if(x > 0){ //Child
int cont = 0;
while(vec->synchronize!=1); //Exit while when father change the variable to 1
int i;
for(i = 0; i < 10; i++){
printf("%d\t",i);
}
vec->synchronize =0; //Return to the father
}
出力のexempleです:
Father
Child
0 1 2 3 4 5 6 7 8 9
cont 1
Father
最初の反復後、プログラムは "while(vec-> synchronize!= 0);"の後にフリーズします。 ...私はproblemaが子プロセスに存在すると思うが、私はなぜ知りません...任意のアイデア?
は
は子供だけ '一度、それが戻って '0'して終了し、それをトグル1 'へ' synchronize'を反転させながら、自分の子プロセスの一部は、1以上を持つべきだと思います。したがって、親プロセスは、(終了した)子プロセスがもう一度共有変数を切り替えるための終わりのないビジー待機で、メインループの2回目の反復でスタックされます。 – pilcrow