簡體   English   中英

C在具有活動等待的子進程之間共享內存時出錯

[英]C Error when sharing memory between child process with active wait

我正在嘗試在子進程和父進程之間使用共享內存來執行程序。 該程序也使用叉子。

該練習的目標是: - 向主動等待的向量發送給孩子(共享記憶)3次

-Child接收vec,打印它並更改同步變量

  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
}   

這是輸出的例子:

     Father
     Child
      0 1   2   3   4   5   6   7   8   9
     cont 1
     Father

在第一次迭代之后,程序在“while(vec-> synchronize!= 0);”之后凍結; ...我猜這個問題存在於兒童過程中,但我不知道為什么......任何想法?

謝謝

我認為你的子進程部分應該還有1個循環

while(cont != 3){
     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);
     }

     ec->synchronize =0;    //Return to the father
     cont++
 }

不知道副手,但我可以告訴你,任何時候兩個線程寫入同一個變量( vec->synchronize ),你就麻煩了。 對於這樣的同步,請允許我推薦管道或信號量 僅當只有一個線程寫入時,或者當您使用其他機制(如信號量或互斥鎖)來控制對共享內存的訪問時,才使用共享內存。

如果您不能使用信號量,請改用信號和信號處理程序。 如果你不能使用信號,我可以看到另外兩個解決方案:

  1. 當代碼處於關鍵區域時(修改共享內存),使用掩碼阻止所有信號。 這樣可以確保數據共享內存不會損壞。

  2. 而不是做while(vec->synchronize!=1)你應該使用原子函數,如Test&Set。 這個問題是在軟件中很難實現。

現在,這些已經不太好的解決方案的最大缺點是它們不能在多處理器系統中工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM