0

我正在尝试使用 Windows 文件映射并使用信号量来制作一个简单的客户端-服务器程序。客户端向服务器发送 2 个号码,服务器计算 nr1+nr2 和 nr1 * nr2。我尝试了一些东西,但它甚至不适用于 1 个客户,我希望它适用于更多客户。这是代码:

服务器:

#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;
}

我到底做错了什么?我应该如何使用信号量?

4

1 回答 1

7

当我打开服务器时,它不会等待客户端。

文档CreateSemaphore

信号量对象的状态在其计数大于零时发出信号,而在其计数等于零时发出无信号。该lInitialCount参数指定初始计数。

lInitialCount=1在创建信号量时通过了。和1 > 0,因此信号量发出信号并WaitForSingleObject立即返回。

您可能希望创建初始计数为 的信号量0,以便在有人调用之前不会发出信号ReleaseSemaphore

于 2013-10-23T18:52:00.527 回答