Codementor Events

See code run - Understand later - 2

Published May 26, 2021Last updated May 27, 2021
See code run - Understand later - 2

We run code successfully, saw the result with very little understand.
It is really better than writing a lot of code, seeing hundreds of errors and giving up studying the new technologies.

This post focuses on how to understand the previous code:

pipe(fd);

We may read man page or tutorial page about the pipe. For example,
https://man7.org/linux/man-pages/man2/pipe.2.html

pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication. The means it is:

  • data channel
  • interprocess communication: parent process sends to child process / child process receives to parent process or child process sends to parent process / parent process receives from child process.

pipe.png

By drawing the picture, we regconize that the child process/parent can write to or read from pipe.
We can imagine that the pipe has two ends: one for 'write' or one for 'read'.
(In fact, when the fork is called, the variable is duplicated)

The next question come: how we know which end is read, which one is write.
We continue to read that above link:

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe

So, if we want to write to pipe, pipefd[1] is used. If we want to read from pipe, pipefd[0] is used.

So far so good. It is time to test.
What is the problem if both parent and child use the read end only?
We edit code and test:

if(childpid == 0)
{
//close(fd[0]);
write(fd[0], string, (strlen(string)+1));
exit(0);
}
else
{
//close(fd[1]);

nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);

}
Run and see the result:
runforever.png

Oh, the program run forever. Now continue to read:

If a process attempts to read from an empty pipe, then read(2) will block until data is available.

In above modified code, the parent waits forever to read from pipe (no data).

Congratulation! We can read the very complex man page by running the simple program.

Next post: other problems can be discovered by this simple code.

Thank you for reading!

Discover and read more posts from Duc Duy Bui
get started