LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-04-2018, 09:14 AM   #1
Hitx11
LQ Newbie
 
Registered: Dec 2017
Posts: 7

Rep: Reputation: Disabled
Need help with fork() called in a while(1) loop


Hello Everyone,

I have this code:-
Code:
int pid =0; 
int main(void)
{
    while(1)
     {
       pid=fork();
       if(pid==0)
         {
           // Child process statements
         }
       else
         {
           wait(0);
           // Parent process statements
         } 
       statement 1;
       statement 2;
       statement 3;
       ...
       ...
       statement n;
     }
}
I have read that statements after calling fork() are duplicated in child and parent process both.

What I would like to know is, to what process would the statements 1 to n would belong to ?

Thanking you in anticipation.

Regards,
Hitx11
 
Old 05-04-2018, 09:31 AM   #2
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: Rocky Linux
Posts: 4,776

Rep: Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212
Assuming that both processes allow the flow to continue, those statements would be executed in both. Either process could, of course, exit, return, or call exec() prior to flowing out of the "if () { } else { }" construct.
 
Old 05-04-2018, 09:47 AM   #3
Hitx11
LQ Newbie
 
Registered: Dec 2017
Posts: 7

Original Poster
Rep: Reputation: Disabled
Dear @rknichols,

Thanks for answering so quickly.

Does the while(1) call belong to child or parent process ?

Thanks
 
Old 05-04-2018, 10:17 AM   #4
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: Rocky Linux
Posts: 4,776

Rep: Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212
Quote:
Originally Posted by Hitx11 View Post
Does the while(1) call belong to child or parent process ?
Both. The child process starts as a complete copy of the parent process, with the only difference being the return value from the fork() call. And to answer the unasked question, yes, if the child process does nothing that breaks that loop, the code you posted would turn into a fork bomb.
 
Old 05-04-2018, 07:18 PM   #5
onebuck
Moderator
 
Registered: Jan 2005
Location: Central Florida 20 minutes from Disney World
Distribution: SlackwareŽ
Posts: 13,923
Blog Entries: 44

Rep: Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158Reputation: 3158
Moderator response

Moved: This thread is more suitable in <Programming> and has been moved accordingly to help your thread/question get the exposure it deserves.
 
Old 05-04-2018, 09:31 PM   #6
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,780

Rep: Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081
Quote:
Originally Posted by rknichols View Post
if the child process does nothing that breaks that loop, the code you posted would turn into a fork bomb.
I think the wait(0) call might keep it below the level of a fork bomb, since it would mean you effectively only have one process running at a time.
 
Old 05-04-2018, 10:11 PM   #7
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: Rocky Linux
Posts: 4,776

Rep: Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212
Quote:
Originally Posted by ntubski View Post
I think the wait(0) call might keep it below the level of a fork bomb, since it would mean you effectively only have one process running at a time.
Yes, not quite a fork bomb, but it still generates an unbounded set of processes, each waiting on a child that never exits.
 
Old 05-05-2018, 02:35 AM   #8
Hitx11
LQ Newbie
 
Registered: Dec 2017
Posts: 7

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by rknichols View Post
Both. The child process starts as a complete copy of the parent process, with the only difference being the return value from the fork() call.
From the book I read, it states that the code after fork() call is duplicated. The while(1) is placed before the fork call. So will it be duplicated? Can you give a pictorial illustration.
Thanks.
 
Old 05-05-2018, 04:37 AM   #9
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,811

Rep: Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306Reputation: 7306
probably you misunderstood: the whole code is duplicated, not only the part below the fork. But duplication occur when fork was called.

probably: http://www.csl.mtu.edu/cs4411.ck/www...rk/create.html
https://www.youtube.com/watch?v=xVSPv-9x3gk
https://en.wikipedia.org/wiki/Fork_(system_call)

Last edited by pan64; 05-05-2018 at 04:40 AM.
 
Old 05-08-2018, 07:55 AM   #10
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,883
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
Quote:
Originally Posted by Hitx11 View Post
From the book I read, it states that the code after fork() call is duplicated. The while(1) is placed before the fork call. So will it be duplicated? Can you give a pictorial illustration.
Thanks.
I can't give you a picture illustration, but I'll try to explain.

First, back to some earlier comments about a fork() bomb. Well, I don't know if that's a term, but it applies. This code will fork() forever.

The wait() does nothing but wait(), it doesn't make things much better.

Ultimately this will fail when you reach system limits for processes.

Now back to your original questions Hitx11,

The function fork() creates an entire copy of the process which calls it, at the time the call occurs.

So say you have a bubble (your loop) and the code is spinning around that loop repeatedly.

You hit that fork() statement and right at that moment you have two completely identical bubbles, except they have different process numbers, "process ID values".

Right after the fork() call, they are different, but not by much:
  1. They have different process ID numbers (PID)
  2. The parent, retains the process ID number it has. It receives a return value from fork() which tells it the PID of the child process it just created
  3. The parent also is linked to that child process, it will receive signals from the child, but this is only noticeable if you write some code to "look" for signals from that child process.
  4. The child is also linked to the parent and it will send signals to the parent process. Signals are sent regardless of whether or not there is code. For instance if the child process exits, it will send a terminate signal to the parent; regardless whether the parent is actively looking for that signal. It will be sent, it will be received, but it may not be viewed. And that's all OK.
  5. If the parent exits, all the children it created must go, and they will, and these are technical explanations of how System V works.
  6. Back to when things return from fork():
    1. There's a missing return case in that code example, fork() can fail and return -1, therefore the parent does not create a child. That's very rare, but it is a possibility.
    2. As stated above, if you get a positive value in return from fork(), you are still the parent, and you've been given the PID of the child process you just created. Moving forwards, your exact copies of each other will now proceed to be different because they'll do different things and their databases of who they are, who their parents and children are, will be different. Meanwhile given that very simple code, they will be very similar in appearance.
    3. When you receive a zero value in return from fork(), then you are the newly created child. You are very much an exact copy of the parent process which created you, with the exception of your PID number, the parent PID which created you, and the memory you occupy in RAM as a process. You are now a fully independent process and can fork() your own children if you wish, or not. You are free to copy whatever the parent who made you is doing, but the background database of who you are, your PID, your location in memory, your stack, your instruction pointer, your time slot to run in the system scheduler, those are all your own. Your only relations to your parent are that when you terminate, with or without failure, you will send them a signal. And they can either listen to it or not.


Bear in mind something that you may have not thought about:
  1. When you start a new command line prompt in Linux - you have used fork().
  2. When you write a program, and then run it on the command line, you have used fork() - the parent for your program which you ran from the command line IS the PID of the command line. You can check this.
  3. Basically EVERY process in Linux is begat from another one. When Linux starts up, it creates a process and that forks other ones, leading to a large collection of processes in the system. Many of them continue forever, until shutdown That's all OK, it is by design.
That code use of fork(), while somewhat demonstrative, (a) is possibly confusing (b) will consume resources and memory and assigned process ID numbers until the system limits stop it, or RAM is exceeded and a system fault occurs (c) it is a pointless exercise because it really does nothing.

I'm sure there are a variety of other reasons for using fork(). I personally used it to create child processes from a master process, which I called a daemon process. The daemon's only purpose was to create the child processes and monitor them. If they died, the daemon would clean up after them, if needed, and then restart them. This was intended to be a system that was headless (embedded) and stayed up as much as possible. In theory, nothing's supposed to die or crash! But we live in a real world, I still make mistakes, made about 5 typing this paragraph, but I'm a fast typist and me hitting backspace rapidly is just common for me.

So I will point you to a number of blogs I've written about architecture which uses fork(), select(), exec(), pipes, and signals() to create children, monitor them, and establish a communications method between them.

It is not the end all-be all of programming, it's just something I'd done for a system and continue to practice because it works for me.

My point here is fork() is #1 a natural thing in the system that is used all the time even if you don't know about it, for instance when you launch a program by way of running it. Meanwhile you can use it with intent within your program, however my argument is besides "for fun" like is shown there, you are best to use it for it's intended purpose. To create another process which you intend to do something with, but maintain the link to your parent, for some reason.

Those blogs show:
- Making the daemon
- Forking the children, and giving them a communications means
- Monitoring the children, and contending with it when they fail

That's the biggest reason for using fork() or a different way to make other processes, making threads (those are similar but different, they are more tightly coupled together than separate processes), you need to know who each other are in the programming domain, so that you can communicate. There are many ways to communicate, however things like shared memory, process signals, pipes - they are more helpful when you have direct knowledge of who your process peer is. Yes, you can learn who a process peer is by looking into the /proc tree, or using other methods like storing information in files, but it is far faster and with greater benefits if you create a child of yourself, things like signals are automatically built in for that case Easier to use them.

The blogs, you may choose to read versus not. Enjoy! And yes they're very old ... so am I

Creating a daemon to launch and monitor your processes - A lot of it is right in here the rest are a supporting cast
Select(2) and why I use it
Using PIPES for Interprocess Communications
USB Receive and Rapid Parse, GPS Example - More programming versus these concepts, but it is an example of a child process that does something and communicates with the parent
How to kill those Zombies - Read the first one and this one if not the others. This is not about an apocalypse, it is about what happens when non-monitored child processes terminate and no one listens to their signal.
 
Old 05-08-2018, 09:16 AM   #11
rknichols
Senior Member
 
Registered: Aug 2009
Distribution: Rocky Linux
Posts: 4,776

Rep: Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212Reputation: 2212
Quote:
Originally Posted by rtmistler View Post
4. The child is also linked to the parent and it will send signals to the parent process. Signals are sent regardless of whether or not there is code. For instance if the child process exits, it will send a terminate signal to the parent; regardless whether the parent is actively looking for that signal. It will be sent, it will be received, but it may not be viewed. And that's all OK.
Ouch! It sends SIGCHLD. A terminate signal (SIGTERM) would tell the parent to terminate (gracefully).
Quote:
5. If the parent exits, all the children it created must go, and they will, and these are technical explanations of how System V works.
Not at all. The orphaned children are adopted by the init process (PID 1). If an interactive shell (bash, specifically) terminates because it received a hangup signal (SIGHUP), it will resend that signal to all jobs, but it's up to each child process to decide what to do with that signal. For an interactive login bash shell, there is also a huponexit to send that SIGHUP when it exits for any reason, but that option is not set by default. And again, a child process can handle that signal in any way it wants.

Last edited by rknichols; 05-08-2018 at 09:19 AM.
 
Old 05-08-2018, 09:48 AM   #12
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,883
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
Thank you for the corrections. I should've noted that some of my info is learned by osmosis and thus may miss an exact mark or two.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Can do I create a folder called dicom in 3 separate folders using a for-loop cropper Linux - Newbie 12 08-08-2014 06:49 AM
Using fork() and pthreads: Can anyone tell me what is happenning in the "for-loop"? CypherManiac Linux - Newbie 8 08-02-2013 12:45 PM
gdb with fork() - not breaking, following multiple child processes in loop TheMac Programming 2 11-02-2011 08:38 AM
[SOLVED] parent called more times - fork - C language wakatana Programming 6 02-27-2011 01:33 PM
Running while loop in c program's fork function aarontwc Programming 2 11-14-2008 09:43 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:07 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration