• Uncategorized

About c : C-pipe-does-not-work-if-I-use-multiple-files

Question Detail

I’m still new to pipes and I want to understand why this is not working.

Assuming I have the following :

main.c :

#include "macros.h"
#include "child_parent.h"

int main()
{
    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    switch(fork())
    {
        case -1:
            perror("fork()");
            exit(EXIT_FAILURE);

        case 0:
            return child();

        default:
            return parent();
    }
}

child_parent.c :

#include "macros.h"
#include "child_parent.h"

int child()
{
    char buf;
    close(pipefd[1]); // Close unused write end

    while(read(pipefd[0], &buf, 1) > 0)
        CHECK(write(STDOUT_FILENO, &buf,1),"write1()");

    CHECK(write(STDOUT_FILENO, "\n" , 1),"write2()");
    close(pipefd[0]);

    return EXIT_SUCCESS;
}

int parent()
{
    const char *msg = "Hello world!\n";

    close(pipefd[0]); // Close unused read end
    CHECK(write(pipefd[1], msg, strlen(msg)),"write3()");
    close(pipefd[1]);

    wait(NULL);

    return EXIT_SUCCESS;
}

child_parent.h :

#pragma once

static int pipefd[2];

int child();
int parent();

macros.h

#pragma once

#define CHECK(func, msg) do {       \
    if ( (func) == -1) {            \
        perror(msg);                \
     }                              \
    }while(0)                       \

So basically I just wanted to test the inter-process communication between anonymous pipes. When compiling the program, it throws the following error:

write3(): Bad file descriptor

Which means that the parent process couldn’t write into the pipe.

But when writing the whole implementation in main.c, the communication will work correctly.

So it has to do with the static int pipefd[2] that is declared in child_parent.h.
What am I doing wrong here ?

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.