服務器代碼下面的一個字符串轉換成共享內存變量。使用信號量共享內存安全寫入
客戶端代碼顯示共享內存中可用的字符串。
全碼: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循環運行時,信號量不會寫入允許寫入,直到客戶端釋放信號量。當客戶端釋放信號
感謝
你試過'男人sem_overview'上命令行? –
是的。我仍然有些掙扎。 – sujin
什麼客戶端服務器通過共享內存進行通信?爲什麼不使用管道或套筒? –