所以,我尝试启动一个使用管道在进程之间进行通信的网络服务器。
我正在考虑创建一个名为 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_t *ctx = {0};
这将 ctx
设置为空指针,尽管有点冗长(大括号不是必需的,尽管它们无害)。在尝试使用 ctx_t
结构之前,您需要在某处分配它。
用途:
cts_t ctx = { { 0, 0 } };
和:
if (pipe(ctx.pipefd) != 0)
…report error etc…
使用 == -1
也可以。
关于c - 管道 "bad address"管道打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792350/