LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how fork works (https://www.linuxquestions.org/questions/programming-9/how-fork-works-908284/)

tarunchawla 10-15-2011 02:40 AM

how fork works
 
#include<iostream>
using namespace std;
void main1();
void main2();
int main()

{
cout<<"tarun";
main1();
main2();
}
void main1()
{
cout<<"parent"<<endl;
pid_t pid;
pid=fork();
if(pid==0)
{
cout<<"child";
}
}
void main2()
{
cout<<"parent2"<<endl;
pid_t pid;
pid=fork();
if(pid==0)
{
cout<<"child2";
}
}

please tell me the output and how fork works?

macemoneta 10-15-2011 03:31 AM

1. If you want to know the output, why not run it yourself?
2. Put code in a code block to retain formatting.
3. Google and Wikipedia answers simple questions like how fork works.

theNbomr 10-15-2011 11:55 AM

In the simplest terms, fork() duplicates the entire process of the process that called fork(). This is called forking/launching a child process, and is how all userspace processes are created in Unix/Linux. The return value of fork() is the process id of the resulting child process. Since the result of calling fork() will be an exact duplicate of the parent process, the child process will execute the same logic as the parent. In doing so, it also tests the return value of fork(), and upon seeing that said return value is zero, recognizes that it is the child process. Usually, the child process logic causes it to perform some different actions, often a call to exec(), which replaces the current process with another, never to return.

Of course there is much greater detail on this subject in your handy man pages. I won't 'tell you the output', as that should be trivial for you to do for yourself, and because it would probably defeat the purpose of the homework exercise.

--- rod.


All times are GMT -5. The time now is 02:58 PM.