Sending messages using pipe - C
<p>I want to make <code>NO_PROC</code> processes, such that every process reads messages from its parent, and then writes those messages and one more message to its child, except in the case of the last process which writes its messages to <code>stdout</code>. So the <em>i'th</em> process will receive <em>i-1</em> messages and will send to child <em>i</em> messages. I must use pipe to communication between processes. I wrote code but something is wrong and I can't find any bug :/. When <code>NO_PROC = 5</code> I want the output to look like 4 lines with "my message", but in output I have one line: "my message" and 3 empty lines, like 3 messages are empty string :/. Note, <code>err.h</code> is my library which gives me function <code>syserr()</code> when something went wrong.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;unistd.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/wait.h&gt;
#include "err.h"

#define NO_PROC 5
#define BUF_SIZE 20

char message[] = "my message";
int parent;
char buf[BUF_SIZE];

int main()
{
    for (int i = 0; i &lt; NO_PROC; ++i) {
        int pipe_dsc[2], buf_len;
        if (pipe(pipe_dsc) == -1)
            syserr("Error in pipe\n");
        pid_t pid = fork();
        if (pid == -1)
            syserr("Error in fork\n");
        else if (pid == 0)
            parent = pipe_dsc[0];
        else {
            for (int j = 0; j &lt; i; ++j) {
                if ((buf_len = read(parent, buf, BUF_SIZE - 1)) == -1)
                    syserr("Error in read\n");
                buf[buf_len &lt; BUF_SIZE - 1 ? buf_len : BUF_SIZE - 1] = '\0';
                if (i == NO_PROC - 1)
                    printf("%s\n", buf);
                else if (write(pipe_dsc[1], buf, sizeof(buf)) != sizeof(buf))
                    syserr("Error in write\n");
            }
            if (i &lt; NO_PROC - 1 &amp;&amp; write(pipe_dsc[1], message, sizeof(message)) != sizeof(message))
                syserr("Error in write\n");
            if (wait(0) == -1)
                syserr("Error in wait\n");
            return 0;
        }
    }
}
</code></pre>