So, im trying to start a webserver that uses pipes to comunicate between process.
I was thinking to make a struct named ctx
to send other info also.
My code looks like this:
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);
}
...
...
}
Output: "ctx pipe error: Bad address"
if instead i declare my program like this, i have no error and the programs continue
webserver.h
int pipefd[2];
webserver.c
int main(int argc, char *argv[]){
if(pipe(pipefd) == -1){
perror("ctx pipe error");
exit(EXIT_FAILURE);
}
...
...
}
Any ideas why i cant open the pipe inside a struct? I still havn't made any forks in the main program.
Thanks.
You're passing a null pointer to a function (system call) pipe()
that doesn't accept null pointers. Don't do that!
ctx_t *ctx = {0};
That sets ctx
to a null pointer, albeit somewhat verbosely (the braces are not necessary, though they're not harmful). You need to allocate the ctx_t
structure somewhere before trying to use it.
Use:
cts_t ctx = { { 0, 0 } };
and:
if (pipe(ctx.pipefd) != 0)
…report error etc…
Using == -1
is also OK.