Codementor Events

See code run - Understand later - 1

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

There are a lot of knowledge of programming languages, libraries to study these days. We can read API, reference manual, docs, ... It is very complex and hard to understand. This may lead to fail to fullfil the expectation and give up.
In this post, I write about one method to make the study more easier.
Assume that we are reading about the fork, pipe.
See the man page:
https://man7.org/linux/man-pages/man2/fork.2.html

The child process and the parent process run in separate memory
spaces. At the time of fork() both memory spaces have the same
content. Memory writes, file mappings (mmap(2)), and unmappings
(munmap(2)) performed by one of the processes do not affect the
other.
...
mmap, setpgid, mlock, mlocall, chrt(1), dbpmda(1), pmcd(1), setsid(1), strace(1), xargs(1), alarm(2), arch_prctl(2), bpf(2), chdir(2), chroot(2), clone(2), eventfd(2), execve(2), _exit(2), fcntl(2), flock(2), getitimer(2), getpid(2), ...
...
With the beginner, it is too complex.
So, we try a small following code (it is easy to find by google):

#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;
        char    string[] = "Hello! Code mentor\n";
        char    readbuffer[80];

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

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

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

Do not read the details.
We understand the simple thing:

  • the parent process creates the child process
  • a pipe is created.
  • the child writes a string in the pipe and then the parent read that string.

Now Run:
https://www.jdoodle.com/c-online-compiler/

Copy code to the website, click Execute button, the result is

Received string: Hello, Code mentor!

run.png

It is very fast and simple. No need to set up the Compiler, Linux or Virtual box envirment. Code has no bug and run perfectly.

It is time to change the code to test such as: remove close(fd[1]); to understand why we have to close the pipe.

Thank you!

Next post: Investigate more details.

Discover and read more posts from Duc Duy Bui
get started
post commentsBe the first to share your opinion
Show more replies