Linux pipe: Bad file descriptor in functions read and write
<p>I'm learning about pipes in C and I have a problem with my code:</p>
<p>My program creates a child process and a pipe between parent process and child process. I'm trying to send a simple string from parent to child through pipe. But for some reason I get an error messages for functions <strong>read</strong> and <strong>write</strong>:</p>
<pre><code>&quot;read error: Bad file descriptor&quot;
&quot;write error: bad file descriptor&quot;
</code></pre>
<p>I have no idea, where the problem is, I've just started learning about pipes in C.</p>
<p>Here's my code:</p>
<pre><code>#include &lt;stdio.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;unistd.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

int err( const char* what )//function that writes errors
{
    perror( what );
    exit( -1 );
}

int main()
{
    int fdes[2]; //File descriptors for pipe
    pid_t pid;
    char string[20] = &quot;Hello World\n&quot;;//string that I want to send to childs process

    int p = pipe( fdes ); //Creating pipe
    if( p &lt; 0 )
        err( &quot;pipe error\n&quot;);

    pid = fork(); //Creating process
    if( pid &lt; 0 )
        err( &quot;fork error\n&quot; );

    if( pid == 0 ) //child
    {
        p = close( fdes[0] ); //Closing unused &quot;write&quot; end of pipe for child
        if( p &lt; 0 )
            err( &quot;close error\n&quot; );

        char str[20]; //I save the message from parent in this string
        int p;
        p = read( fdes[1], str, strlen(str) );// Trying to receive the message and save it in str[]
        if( p &lt; 0 )
            err( &quot;read error\n&quot; );

        printf( &quot;Child received: %s\n&quot;, str );
    }
    else //parent
    {
        p = close( fdes[1] ); //Closing unused &quot;read&quot; end of pipe for parent
        if( p&lt;0 )
            err( &quot;close error\n&quot;);

        p = write( fdes[0], string, strlen( string ) ); //Trying to send the message to child process
        if( p &lt; 0 )
            err( &quot;write error\n&quot; );

        printf( &quot;Parent sent: %s\n&quot;, string );
        
        
    }
    return 0;
}
</code></pre>