Codementor Events

See code run - Understand later - 3

Published May 27, 2021Last updated May 28, 2021
See code run - Understand later - 3

In this post, we will investigate more about the our simple code. In fact, the complexity is being increased.
The program is changed to read/write integer.

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        int data;

        pipe(fd);
        
        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
            close(fd[0]);
            data = 10;
            write(fd[1], &data, sizeof(int));
            exit(0);
        }
        else
        {
            close(fd[1]);

            nbytes = read(fd[0], &data, sizeof(int));
            printf("Received data: %d", data);
        }
        
        return(0);
}

Result is:
Received data: 10

We discovered that the pipe can be used to transfer any type of data such as characters, int. You can change to float, double.
The following code uses double:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        double data;

        pipe(fd);
        
        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
            close(fd[0]);
            data = 10.123;
            write(fd[1], &data, sizeof(double));
            exit(0);
        }
        else
        {
            close(fd[1]);

            nbytes = read(fd[0], &data, sizeof(double));
            printf("Received data: %lf", data);
        }
        
        return(0);
}

Result is:
Received data: 10.123000

Why we take a lot of time to test with integer, float... There are two purposes:

  • More time in this code make us more confident.
  • One question is raised: How the client knows what data is on the pipe.

See the code again:
sizeof(double)
sizeof(int)

The pipe does not care about the data is transfered through it. The child process and parent process should define something called protocol. That means the negotiation: "I transfer 4 bytes of data; You will receive 4 bytes of data. Then you need to treat 4 bytes as integer".

Normally, some bytes at the beginning can be used as the length of the transfered data.

Next post: part 4 - What is the pipe and how it is implemented?

Thank you for reading!

Discover and read more posts from Duc Duy Bui
get started