【问题标题】:Pipe "bad address" on pipe open管道打开时管道“错误地址”
【发布时间】:2020-01-07 13:56:33
【问题描述】:

所以,我试图启动一个使用管道在进程之间进行通信的网络服务器。

我正在考虑创建一个名为 ctx 的结构来发送其他信息。

我的代码如下所示:

webserver.h

typedef struct
{
    int pipefd[2];
} ctx_t;

webserver.c

int main(int argc, char *argv[]){
    ctx_t *ctx = {0};
    if(pipe(ctx->pipefd) == -1){
        perror("ctx pipe error");
        exit(EXIT_FAILURE);
    }
    ...
    ...
}

输出:“ctx 管道错误:地址错误”

如果我这样声明我的程序,我没有错误并且程序继续

webserver.h

int pipefd[2];

webserver.c

int main(int argc, char *argv[]){
    if(pipe(pipefd) == -1){
        perror("ctx pipe error");
        exit(EXIT_FAILURE);
    }
    ...
    ...
}

任何想法为什么我不能打开结构内的管道?我仍然没有在主程序中进行任何分叉。

谢谢。

【问题讨论】:

  • 您将一个空指针传递给一个不接受空指针的函数(系统调用)pipe()。不要那样做。
  • ctx 是一个指针。它的值为零。引用 ctx->pipefd 不好。
  • 你可能指的是ctx_t ctx[] = {0}而不是ctx_t *ctx ...
  • @WilliamPursell — 您可能会从编译器收到有关初始化程序中大括号不足的警告 — 您需要像 ctx_t ctx[] = { { { 0, 0 } } }; 这样的东西来完全支撑(外大括号用于数组,中间大括号用于结构,结构内数组的内部结构)。
  • 我知道gcc 将采用{0} 并将声明的对象初始化为零,但不确定这是否是标准功能。

标签: c linux pipe posix ipc


【解决方案1】:

您将空指针传递给不接受空指针的函数(系统调用)pipe()。不要那样做!

ctx_t *ctx = {0};

这将ctx 设置为空指针,尽管有点冗长(大括号不是必需的,尽管它们无害)。在尝试使用之前,您需要在某处分配 ctx_t 结构。

用途:

cts_t ctx = { { 0, 0 } };

和:

if (pipe(ctx.pipefd) != 0)
    …report error etc…

使用== -1也可以。

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2018-12-18
    • 2016-11-04
    • 2021-05-23
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多