2013-07-19 51 views
2

服務器代碼下面的一個字符串轉換成共享內存變量。使用信號量共享內存安全寫入

客戶端代碼顯示共享內存中可用的字符串。

全碼:available in this github link

Server.c

int main(int argc, char *argv[]) 
{ 
    /* code to create posix shared memory and posix named semaphore */ 

    /* critical section start */ 

    snprintf(shared_msg->content, MAX_MSG_LENGTH, "%s", argv[1]); 

    /* critical section end */ 
} 

Client.c

int main(int argc, char *argv[]) 
{ 
    /* code to open posix shared memory and posix named semaphore */ 

    for(i=0; i<20; i++){ 
     /* critical section start */ 

     //operation of semaphore 
     while(loop < 15){ 
      printf("Type : %d, content : %s\n", shared_msg->type, shared_msg->content); 
      sleep(1); 
      loop++; 
     } 

    /* Critical section end */ 

    loop = 0; 
    printf("loop %d finished\n", i); 
     } 
} 

如何使用上面的代碼(等待和後)POSIX信號,以達到以下要求

  • 客戶端啓動時必須顯示共享內存數據。一旦內部while循環完成後,只有客戶端釋放共享內存。
  • 如果服務器啓動並嘗試將數據寫入共享內存,當客戶端在while循環運行時,信號量不會寫入允許寫入,直到客戶端釋放信號量。當客戶端釋放信號

感謝

  • 在單線服務器必須寫。

  • +0

    你試過'男人sem_overview'上命令行? –

    +0

    是的。我仍然有些掙扎。 – sujin

    +0

    什麼客戶端服務器通過共享內存進行通信?爲什麼不使用管道或套筒? –

    回答

    1

    你想要一個準互斥或二進制信號量,即一次只有一個進程可以訪問資源,在這種情況下,共享內存。所以,這看起來錯誤:

    mysem = sem_open(SEMOBJ_PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG, 2); 
    

    你想要的初始值是1,想要寫的共享內存調用sem_wait遞減CTR爲0,從而迫使任何其他進程調用sem_wait等到值的第一個進程是非零的。換句話說,信號量被鎖定,直到持有它的進程執行sem_post

    你的僞代碼看起來基本上是正確的。 sem_wait當您輸入臨界區域時,sem_post當您退出。根據我的理解,我認爲你的問題在於錯誤地初始化sem_open上的信號量。

    0

    從@Duck的答案我重寫代碼。現在我得到預期的輸出。

    我初始化旗語1 @Duck答案說

    更新server.c

    int main(int argc, char *argv[]) 
    { 
        /* code to create posix shared memory and posix named semaphore */ 
    
        /* critical section start */ 
        sem_wait(mysem); //update 
        snprintf(shared_msg->content, MAX_MSG_LENGTH, "%s", argv[1]); 
    
        /* critical section end */ 
    } 
    

    更新client.c

    int main(int argc, char *argv[]) 
    { 
    /* code to open posix shared memory and posix named semaphore */ 
    
    for(i=0; i<20; i++){ 
        /* critical section start */ 
    
        //operation of semaphore 
        while(loop < 15){ 
         printf("Type : %d, content : %s\n", shared_msg->type, shared_msg->content); 
         sleep(1); 
         loop++; 
        } 
        sem_post(mysem); 
    /* Critical section end */ 
    
        loop = 0; 
        printf("loop %d finished\n", i); 
        } 
    }