管道 "bad address" 打开管道
Pipe "bad address" on pipe open
所以,我正在尝试启动一个使用管道在进程之间进行通信的网络服务器。
我正在考虑创建一个名为 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 pipe error: Bad address"
如果我这样声明我的程序,我没有错误并且程序继续
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_t *ctx = {0};
这将 ctx
设置为一个空指针,尽管有点冗长(大括号不是必需的,尽管它们无害)。在尝试使用它之前,您需要在某处分配 ctx_t
结构。
使用:
cts_t ctx = { { 0, 0 } };
和:
if (pipe(ctx.pipefd) != 0)
…report error etc…
使用== -1
也可以。
所以,我正在尝试启动一个使用管道在进程之间进行通信的网络服务器。
我正在考虑创建一个名为 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 pipe error: Bad address"
如果我这样声明我的程序,我没有错误并且程序继续
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_t *ctx = {0};
这将 ctx
设置为一个空指针,尽管有点冗长(大括号不是必需的,尽管它们无害)。在尝试使用它之前,您需要在某处分配 ctx_t
结构。
使用:
cts_t ctx = { { 0, 0 } };
和:
if (pipe(ctx.pipefd) != 0)
…report error etc…
使用== -1
也可以。