Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fork with c

Tags:

c

fork

It is an academic question so the reason is to understand the output.

I have a code:

int main(int argc, char **argv) {
            int k ;
            while(*(++argv)) {
                    k = fork();
                    printf("%s ",*argv);
            }
    return 0;
    }


running the program with : prog a b
The output is :

  a b a b a b a b

Why do I get this result?

like image 660
igascream Avatar asked Sep 22 '26 09:09

igascream


2 Answers

As suggested by Chris Lutz in the comments, you are observing the effect of a static buffer used by printf being duplicated by the fork() call. The two processes created by the first fork() do not print b (as you could expect, and as happens if you force a flush). They both print a b because they both have a pending, unflushed a in their respective buffers.

There are 4 processes (2^2, including the initial one), they all only really print at exit when the buffer is flushed, and they all have a b in their respective buffers at that time.

like image 178
2 revsPascal Cuoq Avatar answered Sep 23 '26 22:09

2 revsPascal Cuoq


In the beginning argv will point to argv[0] which is the executable file name, it's increased once inside while() to point to argv[1].

Now it hits fork() creating a second thread starting at the same line.

Both threads will write a to their own stdout buffer.

Now argv is moved by 1 character in both instances (inside while()), as they essentially work with copies if I remember that correctly.

The fork in each thread will now create 2 additional copies of the thread (one for each existing thread).

Now the 4 instances will all have the 'a ' still in their stdout buffer that is copied (think so, would be nice if anyone could confirm this) and their argv pointing to b. This one is written as well, so now we've got 4 threads each having 'a b ' in their output buffers.

Once they end, their buffers are flushed resulting in the 'a b a b a b a b ' (essentially being 'a b ', 'a b ', 'a b ', and 'a b ').

Ben's comment can be explained by flushing caused by the linebreaks.

like image 23
Mario Avatar answered Sep 24 '26 00:09

Mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!