Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
For(i=0, i<3, i++){
Fork()
}
Hello, this Code creates 5 process.
How can i create only 3 processes ?
Or how do i create only Child processes ?
Thank you
When you create a fork, both the parent and the newly created child process continue from the point of forking. So, if you have a loop running three times with fork, the parent creates three children, the first child creates two children, and so on. So, your example will result in more than five processes.
When a fork is created, you can record the pid (process ID). In the child process, the pid value of itself will be 0, while the parent process will have the child's pid stored. You can use this to control subsequent forks.
To create three processes, you can use:
pid_t pid;
pid = fork();
// this will be true only in the child process
// so, only the child creates another process, resulting in a total of
// three processes
if (pid == 0) {
fork();
}
After the first call to fork(), both the parent and the child process are executing the for-loop, so both of them execute the second call to fork, and now you have more processes than you wanted. To fix this you need to make the child do something different than the parent. You can tell which process is which by looking at the return value of fork; it returns 0 in the child and a nonzero value in the parent. So, something like this:
fflush(0); // not directly relevant but always a good idea before forking
for (int i = 0; i < 3; i++) {
if (fork() == 0) {
_exit(main_for_child(i)); // very important to use _exit, not exit
}
// control reaches this point only in the parent
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm revising for an operating systems exam and currently trying to understand this processes question:
int main()
{
int v=0;
if(fork())
{
v++;
if(!fork())
{
fork();
v--;
}
}
}
So the question asks to
Draw a tree reflecting the parent-child hierarchy of processes created when the program above is run.
How many separate copies of the integer variable v are created? Discuss what is the value of v at the end of the program for each of the processes in the tree.
The main thing I'm having an issue with is the
if(fork())
line in the code. From looking at other stack overflows I realised that
if(fork()) = if(fork() != 0)
but I'm still having difficulty understanding whether the first if statement creates a child process? Because thats the only way that the second if statement:
(!fork())
can be executed?
This is how far I've got with my current understanding of the question.
screenshot of attempt
Hopefully the diagram is legible! I'd be really grateful for any hints or pointers with this.
Notice that if (fork()) /*etc*/ is exactly the same as
pid_t newtmp = fork();
if (newtmp != 0) /*etc*/
where newtmp is a fresh (new) variable name not occurring in your program (you could use x1, x2 etc.... provided it has no occurrence in your program), and pid_t is some integral type (probably int).
Once you rewrote your code with explicit and unique names given to result of fork you'll understand it better.
BTW, the code is poor taste. When you use fork you need to handle three cases:
the fork failed (e.g. because your system has not enough memory, or because you exceeded some limits) and gives -1
the fork succeeded in the child so gives 0
the fork succeeded in the parent, so gives the pid of the child.
But when you code if (fork()) you are forgetting -or handling incorrectly- the first case (failure). It can rarely happen.
Read carefully (and several times) the fork(2) man page. Notice that fork is difficult to understand.
Regarding limits, be aware of setrlimit(2) (and the ulimit bash builtin).
The answer is
if (fork ())
may or may determine whether a child process was created.
Go to the man page:
http://man7.org/linux/man-pages/man2/fork.2.html
We find that fork () returns three types of values:
-1 => fork() failed
0 => return value in the child process
a positive value => success and the PID of the child process.
Thus the test
if (fork ())
which is the same as
if (fork () != 0)
may succeed whether or not a child process was created. A competently written question would have said
if (fork () > 0)
Assuming everything works correctly:
int main()
{
int v=0;
if(fork()) // Creates a child process that does nothing.
{
v++;
if(!fork()) // Creates a child process that creates a child process (that then does nothing but decrement v).
{
fork();
v--;
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
For the program below:
int main() {
Pid_t pid1, pid2;
Pid1 = fork();
pid2 = fork();
if (pid1 == 0) { /* child process */
thread_create(. . .);
}
if (pid2 == 0) { /* child process */
pthread_create(. . .);
}
fork();
}
a.How many unique processes are created?
b. How many unique threads are created?
Our class has been discussing this for two days. We are told that it is 2 unique threads. However when I replace the pthread_create with a print I am getting more than two. I get this output
Thread 2: 1855 0
Thread 1: 0 1859
Thread 1: 0 0
Thread 2: 0 0
Where Thread 1/2 shows the if statments and pid1 pid2 is printed.
So why is it 2? Can you provide an explanation we can show in class?
The first fork creates a second process from your first process. But the second fork is not guarded by checking the PID, so this fork happens in both processes, resulting in a total of 4 processes. The final fork at the end will then result in 8 processes.
So, when you read the if statements, you have 4 processes. Lets examine the pid values in these processes:
Process 1: Pid1=0, Pid2=0
Process 2: Pid1=0, Pid2=non-0
Process 3: Pid1=non-0, Pid2=0
Process 4: Pid1=non-0, Pid2=non-0
You will see that process 1 will now create 2 threads. Process 2 will create 1 thread, process 3 will create 1 thread, and process 4 will create no threads.
So why is it 2?
As we have seen, it is not. 4 new threads are created (for a total of 12 threads if we included the main thread of each process).
I'm not sure what a "unique" thread is supposed to be in this context, but the number of processes created here is 8; We start with one process, the first fork creates another. Both of those hit the second fork, which creates 2 more processes, and finally all of those 4 hit the last fork making for 8 processes total.
The first pthread_create is hit by the second (first child of the first) process and the child of the second process, whereas the second pthread_create is hit by the child of the second process and the second child of the first process (be very skeptical about this paragraph, I got this mixed up in my head several times so I can see why you'd struggle with this).
So depending on what exactly you're counting, there are 8 "main" threads, 4 "auxiliary" threads or 12 threads total. Not sure how you're supposed to come up with 2, other than the trivial fact that there are 2 calls to pthread_create in the source code.
If you have a very particular definition of "unique thread" that would change this, please edit your answer to include it.
You start with one process, call it PROCESS_A.
After the first fork call you have two processes, PROCESS_A (pid1 > 0) and PROCESS_B (pid1 = 0).
Both PROCESS_A and PROCESS_B then fork again, producing (in total) PROCESS_A, PROCESS_B, PROCESS_C, and PROCESS_D, so we end up with:
First fork situation:
PROCESS_A (pid1 > 0, pid2 > 0) is the parent process of B.
PROCESS_B (pid1 = 0, pid2 > 0) is a child of PROCESS_A (pid1 > 0)
Second fork situation:
PROCESS_C (pid1 > 0 (copied from A), pid2 = 0) is a child of PROCESS_A (pid2 > 0)
PROCESS_D (pid1 = 0 (copied from B), pid2 = 0) is a child of PROCESS_B (pid2 > 0).
Thus, in terms of thread creation:
PROCESS_A doesn't create either thread, because both pid1 and pid2 are non-zero in PROCESS_A.
PROCESS_B creates the first thread but not the second.
PROCESS_C creates the second thread but not the first.
PROCESS_D creates both threads.
So by my count four threads are created.
The final fork call is a red herring. A new process is created, true, but it immediately terminates as there's no code following the last fork.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I've this code that executes some code depending of if the active process is the parent or the child process in an infinite loop:
pid_t childPID;
childPID=fork();
while (1)
{
if (childPID >=0)
{
if (childPID==0)
{
[do child process stuff]
}
else
{
[do parent process stuff]
}
}
else
{
printf("\n Fork failed, quitting!!!!!\n");
return 1;
}
}
Code is simple but there's one very big thing on it for me which I don't understand how it happens although I have a guess:
If not taking into consideration that we're creating 2 processes it looks like childPid is constantly being reasigned which I don't think makes any sense.
So my guess, is that fork creates a childPid for each process, returning a 0 to the parent process and the pid to the child process, even though this syntax makes me think it should only return only one result and assign it to chilPid.
Is my guess correct or is there some other thing involved?
Thank you.
So my guess, is that fork creates a childPid for each process, returning a 0 to the parent process and the pid to the child process, even though this syntax makes me think it should only return only one result and assign it to chilPid.
Exactly that. From the fork reference manual:
RETURN VALUE:
On success, the PID of the child process is returned in the parent, and
0 is returned in the child. On failure, -1 is returned in the parent,
no child process is created, and errno is set appropriately.
so
Is my guess
Why guess if this is precisely defined in the POSIX specification?
From fork(2) linux man page:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately
So childPID is 0 in the child process and is child's pid in parent's process
What fork does is to create a new copy of the actual process to be the child process.
The childPID=fork(); is evalueated in both processes and it returns one and only one value, the trick is that the value is different depending on which of the process is executed. On the parent process it returns the PID of the new process (child), and on the child process returns 0, if fork wasn't succesful returns -1 adn the child process is never created
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm forking, and executing a certain block in the child process. My problem is that my child process never gets into the if statement. Why is this?
if((x = strcmp(subargs[next_redirect], ">")) == 0)
{
pid = fork();
fprintf(stderr, "my PID is %i\n", pid);
if(pid == 0)
{
fprintf(stderr, "the name of our file is %s\n", subargs[i+1]);
fp = creat(subargs[i+1], S_IWUSR | S_IRUSR);
dup2(fp, STDOUT_FILENO);
close(fp);
//create sub-command
makesubcommand(subcommand, subargs, last_redirect + 1, i);
execvp(subcommand[0], subcommand);
}
last_redirect = i;
next_redirect = getnextredirect(subargs, i+2, subargc);
}
My output is
my PID is 11080
my PID is 0
When you fork, the child process receives a PID of 0, correct?
My problem is at if(pid == 0){}. The code in that block never executes.
Your child process is not getting to if because of wait() system call.
The system call wait() blocks the calling process until one of its child processes exits or a signal is received.wait() takes the address of an integer variable and returns the process ID of the completed process. Some flags that indicate the completion status of the child process are passed back with the integer pointer. One of the main purposes of wait() is to wait for completion of child processes.
The execution of wait() could have two possible situations.
If there are at least one child processes running when the call to wait() is made, the caller will be blocked until one of its child processes exits. At that moment, the caller resumes its execution.
If there is no child process running when the call to wait() is made, then this wait() has no effect at all. That is, it is as if no wait() is there.
So remove the wait() system call. and your program will run ok.
Check the call of execvp in your code, which may have errors. You can check the return value of wait to get the child pid or -1.
Apologies. It turns out that my problem was
fprintf(stderr, "the name of our file is %s\n", subargs[i+1]);
I was left thinking that the block was never executed because this wouldn't print anything.
it turns out that there is a problem with subargs.
I appreciate all the help.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :
#include<stdio.h>
int main()
{
int a, b;
b=fork();
printf("\n the value of b = %d",b);
}
The output of this code is following :
Now I don't understand why the output is like this ?
After that i just add a line to my code and output is completely different.
my code is following:
int main()
{
int a, b;
b=fork();
When i run the code the output is following
2389my name is manish
the value of b = 0
Now I'm totally confused about the working of fork() call.
My question are following:
How fork() works?
Where the control goes after the fork() call?
Can any body explain why the outputs of codes written in problem?
Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?
Please explain me the working of fork in the code written in the problem so that I can learn it properly .
It might help to first understand why the word fork was used to name this function. Ever heard of a "fork on the road?" At a fork, the process has to split paths.
First there is a single process executing normally until you reach the fork call. When fork is called, a new process is created, which is identical in virtually every way as the original process, except for the return value of the fork function. The newly created process is called the child process, and hence the process that spawned it is referred to as the parent process.
Since you'd want to perform different tasks for each branch of the fork, it necessitates that you be able to distinguish the child process from the parent process. That's where the return value of fork comes in: fork returns the process id (pid) of the child (the newly created process) to the parent; it returns 0 to the child. Also, should the execution of fork go wrong, the return value is -1.
In your code, you don't distinguish between the child and parent process, so both processes run the entire code that follows after the fork call.
//what the child process looks like after fork is called
int main()
{
int a, b;
b=fork(); // <-- current line of execution: 0 is returned to b
printf("\nmy name is manish\n");
printf("\n my name is anil\n");
printf("\n the value of b = %d",b);
}
// what the parent process looks like after fork is called
int main()
{
int a, b;
b=fork(); // <-- current line: child process id is returned
printf("\nmy name is manish\n");
printf("\n my name is anil\n");
printf("\n the value of b = %d",b);
}
As you can see, both processes have the same code following the fork, hence the output is repeated. Perhaps if you want the parent process to output Manish and the child to output Anil, then you can do something like:
int main()
{
pid_t b; // note that the actual return type of fork is
// pid_t, though it's probably just an int typedef'd or macro'd
b = fork();
if (b == -1) perror("Fork failed");
else if (b > 0) {
printf("My name is Manish\n"); // parent process
else
printf("My name is Anil\n"); // child process
printf("The value of b is %d\n", b);
return 0;
}
Finally, the last comment that must be made is that in your code, the output appears to have been executed first by one process in its entirety and then the other process in its entirety. That may not always be the case. For example, the operating system might allow the parent to execute the 'manish' output, then make this process wait, and handing the cpu over to the child process, which then executes 'manish'. However, the child process may continue and execute 'anil' and 'b' outputs, completing execution of the child process and thus returning execution back to the parent process. Now the parent finishes its execution by outputting 'anil' and 'b' itself. The final output of running this program may look something like:
my name is manish // executed by parent
my name is anil // child
the value of b = 0 // child
my name is anil // parent
the value of b = 2244 // parent
manish.yadav#ws40-man-lin:~$
Take a look at the man page for fork.
Also look at waitpid for proper handling of child processes by parent processes so you don't create zombies.
Edit: In response to your questions in the comments, I'll answer how you can simply run each process consecutively.
int main()
{
pid_t pid;
int i;
for (i=0; i<NUM_PROCESSES; i++)
{
pid = fork();
if (pid == -1)
{
perror("Error forking");
return -1;
}
else if (pid > 0)
{
// parent process
waitpid(-1, NULL, 0); //might want to look at man page for this
// it will wait until the child process is done
}
else
{
// do whatever each process needs to do;
// then exit()
doProcess(i);
exit(0);
}
}
// do anything else the parent process needs to do
return 0;
}
Of course, isn't the best code, but it's just to illustrate the point. The big idea here is the waitpid call, which causes the parent process to wait until the child process it just forked to terminate. After the child prcoess completes, the parent continues after the waitpid call, starting another iteration of the for loop and forking another (the next) process. This continues until all child process have executed sequentially and execution finally returns to the parent.
Fork creates a copy of your current process.
Both the original and the copy continue executing from the point at which fork() was called.
Because your code is executed twice, your print statements are also evaluated twice. In the copied process, the value of b is 0. In the original process, the value of b is the process ID of the copied process.
Once your processes start running concurrently, they will be scheduled independently by your operating system and thus you have no guarantees about when they will actually be run.
Forking is implemented by the OS. It basically creates a child process and starts running it after the fork().
The parent process receives the process id of the file process: b=fork(); b has the process id. The child process get a pid of zero.
(and 4) Because both process can either run in parallel or be time sliced, your output will vary.
You may want to check this out: http://en.wikipedia.org/wiki/Fork_(operating_system)
You'd better start from this.
Here you find explanation and code example.