⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sharestr.c

📁 window下的多线程编程参考书。值得一读
💻 C
字号:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

#define MAX_STRING_SIZE     256
#define FILE_MAPPING_NAME   __TEXT("ShareStrSharedMemory")
#define INITIAL_STRING      __TEXT("(nothing yet)")

int main( int argc, char *argv[]) {
    HANDLE hMapping;
    LPTSTR lpSharedString;
    TCHAR szLocalString[MAX_STRING_SIZE];
    BOOL bCreated;

    // create a named file mapping as shared memory...
    hMapping = CreateFileMapping( (HANDLE) 0xFFFFFFFF, NULL, PAGE_READWRITE, 0,
                                    MAX_STRING_SIZE, FILE_MAPPING_NAME);
    if (hMapping != NULL) {
        if (GetLastError() == ERROR_ALREADY_EXISTS) {
            bCreated = FALSE;
            printf("Opened preexisting file mapping.\n");
        }
        else {
            bCreated = TRUE;
            printf("Created file mapping.\n");
        }
    }
    else {
        printf("Unable to create file mapping, exiting!\n");
        exit(-1);
    }

    // map the memory into this process...
    lpSharedString = (LPTSTR) MapViewOfFile( hMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    if (lpSharedString == NULL) {
        printf("Unable to map into memory, exiting!\n");
        exit(-1);
    }

    // initialize the string if necessary...
    if (bCreated)
        _tcscpy( lpSharedString, INITIAL_STRING); 
    
    while (TRUE) {
        printf( "Type a string to share, [Enter] to display current string, or \"quit\":\n");
        
        // input string...
        _getts( szLocalString);
        
        if (_tcscmp( szLocalString, __TEXT("quit")) == 0) {
            // quit...
            break;
        }
        else if (szLocalString[0] == __TEXT('\0')) {
            // show the string...
            printf( "Current string is '%s'.\n", lpSharedString);
        }
        else {
            // set the string...
            _tcscpy( lpSharedString, szLocalString);
        }
    }

    // unmap the memory...
    UnmapViewOfFile(lpSharedString);

    // close our handle to the file mapping object...
    CloseHandle(hMapping);

    // exit...
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -