【问题标题】:My first windows named pipe, not sure what is wrong我的第一个 Windows 命名管道,不知道出了什么问题
【发布时间】:2012-11-25 14:39:15
【问题描述】:

编辑:这是完整的代码,忽略罗马尼亚语 cmets。还有 2 或 3 个名字未翻译自罗马尼亚语:http://pastebin.com/JjtayvXX

我正在尝试学习操作系统的基础知识,现在我在 windows 下使用命名管道,但我不知道出了什么问题。

老实说,我正在研究一个朋友做过的例子,但他和我一样糟糕,如果不是更糟的话。虽然 hi 的程序有效(尽管它做了其他事情),但他无法解释任何事情,很可能只是从某个地方复制的,仍然......不重要,我想说的是我从示例中学习,而不是专业的.

服务器收到来自客户端的消息,返回最大值和最小值。

服务器.c:

#include "windows.h"
#include "stdio.h"

struct Msg {
int numbers[20];
int length;
};

...

int main () {

HANDLE inputPipe, outputPipe; 
Msg msg;

while (true) {

inputPipe = CreateNamedPipe ("\\\\.\\pipe\\Client2Server",
                 PIPE_ACCESS_INBOUND,
                 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 
                 PIPE_UNLIMITED_INSTANCES,
                 0, //Numb of output bytes
                 sizeof(Msg),  // Numb of input bytes
                 0, // Wait forever
                 NULL); // Don't know how to use security

ConnectNamedPipe (inputPipe,NULL);

    // Here is where the server dies
    ReadFile (inputPipe, &msg,sizeof(Msg),NULL,NULL); 

现在客户端.c:

struct Msg {
int numbers[20];
int length;
};


int main () {

HANDLE outputPipe, inputPipe;
Msg msg;

    // @misc: read data from keyboard, create msg   

outputPipe = CreateFile ("\\\\.\\pipe\\Client2Server",
            GENERIC_WRITE,
            FILE_SHARE_READ, // * comment after code
            NULL, // again, I know nothing about security attributes
            CREATE_ALWAYS, // either create or overwrite
            0,
            NULL);

// Here is where it dies
WriteFile (outputPipe, &msg, sizeof(Msg), NULL, NULL);

我得到访问冲突写入位置 0x00000000。不知道为什么。

  • 我希望这个进程只写,而另一个进程(服务器)只读。 FILE_SHARE_READ 好吗?

另外我不知道如何处理 CreationDisposition / FlagsAndAttributes(CreateFile 的最后两个参数),它们可以吗?

【问题讨论】:

    标签: c named-pipes


    【解决方案1】:

    编辑:添加实际答案,参考其他主题,自己尝试过

    WriteFile()'s第四个参数(指向将存储字节数的变量的指针)不应为空。根据 API 描述,如果第五个参数lpOverlapped 不为空,则此参数只能为空。

    在此处查看类似主题: Why does WriteFile crash when writing to the standard output?


    您能否检查/打印ReadFile()(如果返回=0FALSE 则失败)和client.c CreateFile()(如果返回INVALID_HANDLE_VALUE 则失败)的返回值以查看它们是否成功?

    如果失败,能否在调用后立即打印GetLastError()返回的值,以便我们看到具体的错误?

    【讨论】:

    • 我试过try {WriteFile (outputPipe, &msg, sizeof(Msg), NULL, NULL);} catch(int e) { printf("%d, Error: %d", GetLastError, e); } 但它似乎不起作用,仍然认为没有处理异常。我只能说我在KernelBase.dll 内得到了一个Access violation writing location 0x00000000
    • 哦。 WriteFile() 的第四个参数是可选的(可以为空)仅当第五个参数 lpoverlapped 不为空时。 stackoverflow.com/questions/8195608/…
    • 好吧,我不知道我是怎么错过的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2011-11-08
    • 2015-04-14
    • 1970-01-01
    • 2021-10-06
    • 2023-04-02
    相关资源
    最近更新 更多