2013-10-23 42 views
0

我正在嘗試使用Windows文件映射製作一個簡單的客戶端服務器程序並使用信號量。客戶端向服務器發送2個號碼,服務器計算nr1 + nr2和nr1 * nr2。我嘗試了一些,但它甚至不適合1客戶端,我希望它爲更多的客戶端工作。下面的代碼:信號量上的WaitForSingleObject不會等待,立即返回

服務器:

#include <windows.h> 
#include <stdio.h> 
#include <iostream> 
using namespace std; 

typedef struct { 
    int nr1; 
    int nr2; 
} Mesaj; 

int main(int argc, char** argv) { 

    Mesaj* mesaj; 

    HANDLE createSemaphore = CreateSemaphore(NULL, 1, 1, "Semafor"); 
    if (createSemaphore == NULL || createSemaphore == INVALID_HANDLE_VALUE) { 
     wcout << "Failed to create a semaphore\n"; 
    } else { 
     wcout << "Created the semaphore\n"; 
    } 

    HANDLE hMemory = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, 
      PAGE_READWRITE, 0, sizeof(Mesaj), "SharedMemory"); 

    WaitForSingleObject(createSemaphore, INFINITE); 

    mesaj = (Mesaj*) MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, sizeof(Mesaj)); 

    printf("The numbers received are: %d, %d\n", mesaj->nr1, mesaj->nr2); 

    int produs = mesaj->nr1 * mesaj->nr2; 
    int suma = mesaj->nr1 + mesaj->nr2; 

    printf("\nSuma numerelor este: %d iar produsul lor este: %d", suma, produs); 

    ReleaseSemaphore(createSemaphore, 1, NULL); 

    Sleep(INFINITE); 

    return 0; 
} 

客戶端:

#include <windows.h> 
#include <stdio.h> 
#include <iostream> 
using namespace std; 

typedef struct { 
    int nr1; 
    int nr2; 
} Mesaj; 

int main(int argc, char** argv) { 

    Mesaj* mesaj, *mesaj2; 

    mesaj2 = (Mesaj*) malloc(sizeof(Mesaj)); 

    HANDLE hMemory = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, 
      "SharedMemory"); 

    if (hMemory == NULL) { 
     wcout << "Error at OpenFileMapping\n"; 
    } 

    HANDLE openSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS,TRUE,"Semafor"); 
    if(openSemaphore != NULL || openSemaphore != INVALID_HANDLE_VALUE){ 
     wcout<<"the semaphore is opened\n"; 
    } 

    mesaj2 = (Mesaj*) MapViewOfFile(hMemory, FILE_MAP_WRITE, 0, 0, 
      sizeof(Mesaj)); 

    int nr1 = 0, nr2 = 0; 
    printf("Give a number: "); 
    scanf("%d", &nr1); 
    printf("Give another number: "); 
    scanf("%d", &nr2); 

    mesaj2->nr1 = nr1; 
    mesaj2->nr2 = nr2; 

    if (mesaj2 == NULL) { 
     wcout << "Error\n" 
    } else { 
     wcout << "I sent " << mesaj2->nr1 << " and " << mesaj2->nr2 << endl; 
    } 


    system("pause"); 
    return 0; 
} 

我究竟在做什麼錯?我應該如何使用信號燈?

+1

請更具體地說你的意思是「不工作」。首先,它並不表示你曾經發出過信號量的信號。另一方面,服務器收到一條消息後退出。第三件事,兩個客戶端正在修改相同的內存,這可能導致數據損壞。 –

+0

不起作用,因爲當我打開服務器時,它不會等待客戶端發送數字,之後它不會執行任何操作。 – MathMe

+0

如果問題是'WaitForSingleObject'沒有等待就返回,那就說出來,並刪除所有的共享內存,因爲它與你的問題無關。請參見http://sscce.org/ –

回答

6

當我打開服務器時,它不會等待客戶端。

The documentation for CreateSemaphore

當其計數是大於零的信號量對象的狀態用信號通知,並且無信號時其計數等於零。 lInitialCount參數指定初始計數。

您在創建信號量時通過了lInitialCount=1。和1 > 0,所以信號被髮送並且WaitForSingleObject立即返回。

你大概想要創建一個初始計數爲0的信號量,以便在有人調用ReleaseSemaphore之前不會發出信號。