Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Системное программирование и WinAPI > Запись в анонимный канал


Автор: littlegreg 4.4.2011, 11:31
Всем привет, только начинаю изучать WinAPI и столкнулся с проблемой при записи в анонимный канал, данные в него не записываются, помогите исправить ошибку.

клиент
Код

#include <windows.h>
#include <conio.h>

int main(int argc, char *argv[])
{
    HANDLE hWritePipe;

    hWritePipe = (HANDLE)atoi(argv[1]);
    //wait for command to start write into anonymous pipe
    _cputs("Press any key to start communication.\n");
    _getch();
    //write into AP
    for (int i = 0; i < 10; i++)
    {
        DWORD dwBytesWritten;
        if (!WriteFile(hWritePipe, &i, sizeof(i), &dwBytesWritten, NULL))
        {
            _cputs("Write to file failed.\n");
            _cputs("Press any key to finish.\n");
            _getch();
            return GetLastError();

        }
        _cprintf("The number %d is written to the pipe.\n", i);
        Sleep(500);
    }
    //close pipe descriptor
    CloseHandle(hWritePipe);

    _cputs("The process finished writing to the pipe.\n");
    _cputs("Press any key to exit.\n");
    _getch();

    return 0;
}


сервер
Код

#include <windows.h>
#include <conio.h>

int main()
{
    char lpszComLine[80];   //for comline

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    HANDLE hWritePipe, hReadPipe, hInheritWritePipe;

    //create anonymous pipe
    if (!CreatePipe(
                    &hReadPipe, //descriptor for read
                    &hWritePipe,    //descriptor for write
                    NULL,   //security attributes by default
                            //hReadPipe and hWritePipe unheritable
                    0)) //buffer size by default
    {
        _cputs("Create pipe failed.\n");
        _cputs("Press any key to finish.\n");
        _getch();
        return GetLastError();
    }
    else _cputs("Pipe created succesfully.\n");
    //create inheritable replicate of hWritePipe
    if (!DuplicateHandle(
                         GetCurrentProcess(),   //current process descriptor
                         hWritePipe,    //initial pipe descriptor
                         GetCurrentProcess(),
                         &hInheritWritePipe,    //pipe new descriptor
                         0,
                         TRUE,  //new descriptor is inheritable
                         DUPLICATE_SAME_ACCESS))    //access unchanged
    {
        _cputs("Duplicate handle failed.\n");
        _cputs("Press any key to finish.\n");
        _getch();
        return GetLastError();
    }
    else _cputs("Duplicate created succesfully.\n");
    //close unnecessary descriptor
    CloseHandle(hWritePipe);
    //set attributes for new descriptor
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    //form comline
    wsprintf(lpszComLine, "D:\\Code\\Client.exe %d",
             (int)hInheritWritePipe);
    //launch new console process
    if (!CreateProcess(
                       NULL, //process name
                       lpszComLine, //com line
                       NULL,    //sec attrs by default
                       NULL,    //sec attrs of primary thread by default
                       TRUE,    //inheritable descriptors of current process
                                //are inherited by new process
                       CREATE_NEW_CONSOLE,
                       NULL,   //use environment of process-ancestor
                       NULL,    //current disk and directory
                       &si,     //main window look by default
                       &pi      //here will be descriptors and identificators
                                //of new process and its primary descendant
                                ))
    {
        _cputs("Create process failed.\n");
        _cputs("Press any key to finish.\n");
        _getch();
        return GetLastError();
    }
    else _cputs("Process created succesfully.\n");
    //close descriptors of new process
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    //close unnecessary descriptor of pipe
    //read from anonymous pipe
    for (int i = 0; i < 10; i++)
    {
        int nData;
        DWORD dwBytesRead;
        if (!ReadFile(hReadPipe, &nData, sizeof(nData), &dwBytesRead, NULL))
        {
            _cputs("Read from the pipe failed.\n");
            _cputs("Press any key to finish.\n");
            _getch();
            return GetLastError();
        }
        _cprintf("The number %d is read from the pipe.\n", nData);
    }
    //close pipe descriptor
    CloseHandle(hReadPipe);

    _cputs("The process finished reading from the pipe.\n");
    _cputs("Press any key to exit.\n");
    _getch();

    return 0;
}

Автор: littlegreg 4.4.2011, 11:53
если подставлять другой буфер в WriteFile и ReadFile то все работает, но как мне при считывании получить те же значения, что я записывал.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)