One Way Communication with Pipe in Linux

Pipe uses kernel buffer to store data. It is a unidirectional read/write buffer and connects two processes. Each end (read or write) Pipe mimics a file operation. A process can choose to read or write (but not both). The processes have to use at least two pipes for two-way communication.

Example Communication

  • Parent process can talk to a child with an EOF. Just close its write end of the pipe. The child would get EOF on reading.

Example

#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <assert.h>

int main()
{
    int contact[2];
    pipe(contact);

    int fd = fork();
    if (fd == 0) { // child
       char c;
       close(contact[1]); // close the write end.

       while (read(contact[0], &c, 1) > 0) // each call checks for EOF.
           printf("c=%c", c);
       close(contact[0]);
       exit(0);
    } else { // parent
        close(contact[0]); // close the read end.

        write(contact[1], "X", 1);
        close(contact[1]); // child sees EOF
        wait(NULL);
        exit(EXIT_SUCCESS);
    }
    return 1;
}

References

Written with StackEdit.


Pre-Deployment Checklist for Developers

  1. Handled all error conditions?
    Have you checked each error and handled or propagated upstream?

  2. Returned appropriate error code
    Please return proper error code & detailed error message to callers.

    msg := fmt.Printf("[fname] failed in Redis Set err=%s ret=%d", err, ret)
    ret errRedis
    
  3. Added logs for each failure
    It will help you narrow down the trouble code.

  4. Successful build with lint
    lint keeps your code clean.

  5. Formatting fixes (gofmt)
    Always follow the coding standard of the language, especially symbol names.

  6. Code reviews by at least two people.

  7. Unit Testing (docker compose)
    UT is easy and catches stupid bugs. There are many ways to test the code. The easiest is just the functions you’ve added. Stub any call you don’t or can’t test.

  8. Scale testing (for finding a resource such as sockets, memory leaks)
    UT is ineffective catching serial and slow bugs. These are the most troublesome problems that can be caught using heavy load & volume testing

  9. Staging deployment

  10. Finally, live on production 🙂