0

我有以下代码可以使用信号量连续 R/W 到 sherad 内存。但是当代码试图访问内存进行读取时,它会失败。我找不到问题所在。任何帮助都非常感谢......这是完整的代码:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <cstdlib>
#include<iostream>

#define BUF_SIZE    255
#define TREAD_COUNT 2
#define MAX_SEM_COUNT 1

using namespace std;

char name[]="Global\\MyFileMappingObject";
char* message ="Message from first process.";
char ReadBuffer[BUF_SIZE];
char WriteBuffer[BUF_SIZE];

DWORD WINAPI ReadData( LPVOID );
DWORD WINAPI WriteData( LPVOID );

HANDLE HandleOfTreads[TREAD_COUNT];
HANDLE ghSemaphore;
HANDLE ReadHandleToMapFile;
HANDLE WriteHandleToMapFile;

DWORD ThreadID;

char* PBufForRead;
char* PBufForWrite;
string ReadString;
char PBufForReadPrev[BUF_SIZE];


int _tmain() {

    /*================ Semaphore ======================= */
    ghSemaphore = CreateSemaphore(
                      NULL,           // default security attributes
                      MAX_SEM_COUNT,  // initial count
                      MAX_SEM_COUNT,  // maximum count
                      "name");          // named semaphore

    if (ghSemaphore == NULL) {
        printf("CreateSemaphore error: %d\n", GetLastError());
        return 1;
    }

    /*================ Read Tread====================== */
    HandleOfTreads[0] = CreateThread(
                            NULL,       // default security attributes
                            0,          // default stack size
                            (LPTHREAD_START_ROUTINE) ReadData,
                            NULL,       // no thread function arguments
                            0,          // default creation flags
                            &ThreadID); // receive thread identifier

    if( HandleOfTreads[0]== NULL ) {
        printf("CreateThread error: %d\n", GetLastError());
        return 1;
    }



    /*============ Write Tread=============== */
    HandleOfTreads[1]= CreateThread(
                           NULL,       // default security attributes
                           0,          // default stack size
                           (LPTHREAD_START_ROUTINE) WriteData,
                           NULL,       // no thread function arguments
                           0,          // default creation flags
                           &ThreadID); // receive thread identifier

    if(HandleOfTreads[1] == NULL ) {
        printf("CreateThread error: %d\n", GetLastError());
        return 1;
    }


    /*============ close handles ============= */
    // Wait for all threads to terminate
    WaitForMultipleObjects(TREAD_COUNT,  HandleOfTreads, TRUE, INFINITE);

    // Close thread handles
    for( int i=0; i < TREAD_COUNT; i++ )
        CloseHandle( HandleOfTreads[i]);


    return 0;

}



/*======================= Write data====================== */
DWORD WINAPI ReadData( LPVOID lpParam) {

      cout<<"write"<<endl;

    UNREFERENCED_PARAMETER(lpParam);

    DWORD dwWaitResult;

    while(1) {
        dwWaitResult = WaitForSingleObject(
                           ghSemaphore,   // handle to semaphore
                           INFINITE);           // infinite time-out interval
        cout<<"write got the semaphore"<<endl;


        switch (dwWaitResult) {
            // The semaphore object was signaled.
        case WAIT_OBJECT_0:


            WriteHandleToMapFile = CreateFileMapping(
                                      INVALID_HANDLE_VALUE,    // use paging file
                                      NULL,                    // default security
                                      PAGE_READWRITE,          // read/write access
                                      0,                       // maximum object size (high-order DWORD)
                                      BUF_SIZE,                // maximum object size (low-order DWORD)
                                      name);                 // name of mapping object

            if (WriteHandleToMapFile== NULL) {
                _tprintf(TEXT("Could not create file mapping object for write(%d).\n"),
                         GetLastError());
                return 1;
            }

            PBufForWrite= (LPTSTR) MapViewOfFile(WriteHandleToMapFile,   // handle to map object
                                                FILE_MAP_ALL_ACCESS, // read/write permission
                                                0,
                                                0,
                                                BUF_SIZE);

            if ( PBufForWrite== NULL) {
                _tprintf(TEXT("Could not map view of file for write (%d).\n"),
                         GetLastError());

                CloseHandle(WriteHandleToMapFile);

                return 1;
            }

            getline(cin,ReadString);
            strcpy(ReadBuffer,ReadString.c_str());
            CopyMemory((PVOID) PBufForWrite, ReadBuffer, (_tcslen(message) * sizeof(TCHAR)));


              UnmapViewOfFile((void*)PBufForWrite);
              CloseHandle(WriteHandleToMapFile);
              cout<<"write released the memory"<<endl;
            // Release the semaphore when task is finished

            if (!ReleaseSemaphore(
                        ghSemaphore,  // handle to semaphore
                        1,            // increase count by one
                        NULL) ) {     // not interested in previous count
                printf("ReleaseSemaphore error: %d\n", GetLastError());
            }

            cout<<"write released the semaphore"<<endl;

            break;

            // The semaphore was nonsignaled, so a time-out occurred.
        case WAIT_TIMEOUT:
            printf("Thread %d: wait timed out\n", GetCurrentThreadId());
            break;
        }


    }
}

/*======================= Read data====================== */
DWORD WINAPI WriteData( LPVOID lpParam)
{
    UNREFERENCED_PARAMETER(lpParam);
    cout<<"read"<<endl;

    DWORD dwWaitResult;

    while(1)
        {
        dwWaitResult = WaitForSingleObject(
                           ghSemaphore,   // handle to semaphore
                           INFINITE);           // zero-second time-out interval
        cout<<"read got the semaphore"<<endl;

        switch (dwWaitResult)
        {
            // The semaphore object was signaled.
        case WAIT_OBJECT_0:

             Sleep(100);
            ReadHandleToMapFile = OpenFileMapping(
                                       FILE_MAP_ALL_ACCESS,   // read/write access
                                       FALSE,                 // do not inherit the name
                                       name);               // name of mapping object

            if (ReadHandleToMapFile == NULL) {
                printf(TEXT("Could not open file mapping object for read (%d).\n"),GetLastError());
                cout<<"read exited"<<endl;
                return EXIT_SUCCESS;
            }


                PBufForRead= (LPTSTR) MapViewOfFile(ReadHandleToMapFile, // handle to map object
                                                     FILE_MAP_ALL_ACCESS,  // read/write permission
                                                     0,
                                                     0,
                                                     BUF_SIZE);

                if ( PBufForRead== NULL) {
                    printf(TEXT("Could not map view of file for write (%d).\n"),GetLastError());

                    CloseHandle(ReadHandleToMapFile);
                    system("PAUSE");
                    return EXIT_SUCCESS;

                }

                if(strcmp( PBufForRead,  PBufForReadPrev)) {
                    cout<< PBufForRead<<endl;
                }

                strcpy(  PBufForReadPrev, PBufForRead);


                UnmapViewOfFile((void*)PBufForRead);
                CloseHandle(ReadHandleToMapFile);
                 cout<<"read release the memory"<<endl;

                // Release the semaphore when task is finished

                if (!ReleaseSemaphore(
                            ghSemaphore,  // handle to semaphore
                            1,            // increase count by one
                            NULL) ) {     // not interested in previous count
                    printf("ReleaseSemaphore error: %d\n", GetLastError());
                }

                cout<<"read selased the semaphore"<<endl;
                break;

                // The semaphore was nonsignaled, so a time-out occurred.
            case WAIT_TIMEOUT:
                printf("Thread %d: wait timed out\n", GetCurrentThreadId());
                break;
            }

    }
}
4

0 回答 0