I'm trying to understand how to create fork trees,is there any simple way to understand that?
Exemple:
include<stdio.h>
include<unistd.h>
void main(){
fork();
if fork();
if fork();
fork();
sleep(10);
}
Every time you are calling fork() you are creating a Child that has the exact code the father has until this moment, but its own memory map.
Then you have to 2 processes with the same code. If you want to make them do something different you have to use fork()'s return. Fork returns the pid of the child and ''assigns'' it at Father's memory. Through that mechanism Father can refer to the child using its pid (process ID) which is only known to him. If child tries to see the exact pid created for it through fork(), it simply can't and would be zero (because fork return PID to a process for other child processes).
Example code of the above is the bellow:
void main(void)
{
char sth[20]="something";
pid_t pid;
pid = fork(); // Create a child
// At this line (so this specific comment if you may like) has 2 processes with the above code
printf("I am process with ID<%ld> and i will print sth var <%s>", getpid(),sth);
// The above printf would be printed by both processes because you haven't issued yet a way to make each process run a different code.
// To do that you have to create the following if statement and check PID according to what said above.
if (pid == 0) // If PID == 0, child will run the code
printf("Hello from child process with pid <%ld>",getpid());
printf(", created by process with id <%ld>\n",getppid());
else // Else the father would run the code
printf("Hello from father process with pid <%ld>",getpid());
}
I tried to be as naive as i could. Hope it helps somehow.
From linux manual:
fork() creates a new process by duplicating the calling process.
Basically it creates a new process, referred to as the child, which is an exact duplicate, with same code, of the calling process, referred to as the parent, except for few things (take a look at man fork). It returns the child process ID if you're the parent, 0 if you're the child or -1 (and sets errno) to the parent on failure. Here's a code example of a fork tree:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
/*
* I'm going to create a fork tree
*
*/
int main(){
pid_t pid; /*Use it for fork() calls*/
pid = fork(); /*Generating the first child*/
if(pid == 0){ /*I'm the child*/
pid_t pid_child = fork();
if(pid_child == 0){ /*I'm the grandchild*/
printf("I'M THE GRANDCHILD\n");
return 0; /*Terminates the new process*/
}else if(pid_child > 0){ /* I'm the child*/
waitpid(pid_child,NULL,0);
printf("I'M THE CHILD\n");
return 0; /*Terminates the new process*/
}
}else if(pid > 0){ /*I'm the parent*/
waitpid(pid,NULL,0); /*Waiting for the child*/
printf("I'M THE PARENT\n");
}
return 0;
}
Related
after hours of searching I ended up here. Here's my problem:
I have an exercise I need to do.The code given is this:
int main(){
int x,y,z....;
//
fill the gap
//
printf("A");
//
fill the gap
//
printf("B");
return(0);
}
I must print exactly "AAAAABBB" with using ONLY fork(),if and exit().
(no "wait", no multiple "printf", no "sleep". no "for")
How could I do it? I have tested it in online IDEs but I just cant print them in this exact way. The output is always confusing (AABBBAA, ABABABAA etc.) I can't seem to understand how to give priority to the parent or child without using anything but fork() and if.
Any tip is appreciated.
What you are supposed to be learning here is that fork() duplicates your process - at the point of the fork(). It returns a Process IDentifier (PID) number to the parent process, and zero to the child process.
So by simply watching the return of the fork(), the execution path can determine if they are the parent or child process.
Thus to implement the problem, I took the approach of controlling everything from the single parent process, and having the child simply output a letter, then exit() - which terminates the process.
It would be much nicer with a for() loop, but that was not allowed.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid == 0)
{
// child process only
printf("A");
exit(0);
}
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid == 0)
{
// child process only
printf("B");
exit(0);
}
return 0;
}
Note: I suspect that it may occasionally get mixed up due to system load, scheduling, etc. But in all my tests I received the correct answer.
I have an assignment that is asking me to identify the values of the process IDs at lines A, B, C, and D, assuming that the actual pids of the parent and child are 2600 and 2603, respectfully.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(){
pid_t pid, pid1;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if(pid == 0){ /* child process */
pid1 = getpid();
printf("child: pid = %d", pid); /* A */
printf("child: pid1 = %d", pid1); /* B */
}
else { /* parent process */
pid1 = getpid();
printf("parent: pid = %d", pid); /* C */
printf("parent: pid1 = %d", pid1); /* D */
wait(NULL);
}
}
I've already been given the solutions for the problem, but I'm having trouble understanding the fork() function. Why would it return EITHER -1, 0, or some positive number? Why does it not consistently return a certain value? For example, when we assign pid = fork(), it can be a value of -1, 0, or some positive number. Even if I know that, I don't know how the values become what they are. I know that, initially, the child process is given a copy of the parent data. Ordinarily, my tactic is to step through the code line-by-line and adjust the variables as they are modified to determine output, but this example seems nondeterministic. I feel like I'm viewing this problem completely wrong, but I don't know how to change my thought process. I've reviewed the documentation for fork() here but it didn't clarify anything for me.
Additionally, why don't we use a get function, i.e. pid.getID() in the if/else-if statements? Doesn't this mean that pid_t and int are equivalent?
A step-by-step explanation of this code would be greatly appreciated.
For reference, the solutions are 0, 2603, 2603, and 2600.
fork() creates a new process that's an almost exact duplicate of the original process. Both processes continue running, starting from the return of the fork() function. In the parent process, fork() returns the PID of the child (a positive number), while in the child process fork() returns 0 (that's how it knows that it's the child).
If, for some reason, the system wasn't able to create a new process, fork() returns -1 in the parent instead of the child's PID, and errno is set to the error code with the reason for the failure.
You could do an equivalent test using getpid(), it would just be more work:
pid_t parentPID = getpid();
fork();
pid_t myPID = getpid();
if (myPID == parentPID) {
// this is the parent
} else {
// this is the child
}
Having fork() return 0 in the child simplifies it, since you get all the information you need from that one call, instead of having to call getpid() twice.
I wanna create spare process (child?) in specific function called eg. void process(). I want just to create that child process and do nothing with it. I just wanna it alive and do nothing while main() of my app will be working as I want.
In some point of my app's main() I will be killing child process and then respawn it again. Any ideas how to do that ?
I have something like that but when I'm using this function to create process I get everything twice. Its like after initiation of process() every statement is done twice and i dont want it. After adding sleep(100) after getpid() in child section seems working fine but I cannot kill it.
int process(int case){
if(case==1){
status=1;
childpid = fork();
if (childpid >= 0) /* fork succeeded */
{
if (childpid == 0) /* fork() returns 0 to the child process */
{
printf("CHILD PID: %d\n", getpid());
}
/* fork() returns new pid to the parent process *//* else
{
}*/
}
else
{
perror("fork");
exit(0);
}
}
else{
if(status!=0){
status=0;
//kill!!!!
system(a); //getting kill -9 PID ; but PID is equal 0 here...
printf("\nkilling child");
}
}
}
how to just spawn new child process and let it just exist, like some sort of worker in C#?
Assuming you are in Linux, here's an example that might clarify your view: parent process spawns a child, the child calls pause() which suspends it until a signal is delivered, and finally parent process kill's the child with SIGKILL.
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int main()
{
pid_t pid;
pid = fork();
if (pid < 0) { perror("fork"); exit(0); }
if (pid == 0) {
printf("Child process created and will now wait for signal...\n");
pause(); //waits for signal
}
else {
//do some other work in parent process here
printf("Killing child (%ld) from parent process!", (long) pid);
kill(pid, SIGKILL);
}
return 0;
}
Please note that fork() returns:
<0 on failure
0 in child process
the child's pid in parent process.
I'm studying computer systems and I've made this very simple function which uses fork() to create a child process. fork() returns a pid_t that is 0 if it's a child process. But calling the getpid() function within this child process returns a different, nonzero pid. In the code I have below, is newPid only meaningful in the context of the program, and not to the operating system? Is it possibly only a relative value, measured against the pid of the parent?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
void unixError(char* msg)
{
printf("%s: %s\n", msg, strerror(errno));
exit(0);
}
pid_t Fork()
{
pid_t pid;
if ((pid = fork()) < 0)
unixError("Fork error");
return pid;
}
int main(int argc, const char * argv[])
{
pid_t thisPid, parentPid, newPid;
int count = 0;
thisPid = getpid();
parentPid = getppid();
printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
if ((newPid = Fork()) == 0) {
count++;
printf("I am the child. My pid is %d, my other pid is %d\n", getpid(), newPid);
exit(0);
}
printf("I am the parent. My pid is %d\n", thisPid);
return 0;
}
Output:
thisPid = 30050, parent pid = 30049
I am the parent. My pid is 30050
I am the child. My pid is 30052, my other pid is 0
Lastly, why is the child's pid 2 higher than the parent's, and not 1? The difference between the main function's pid and its parent is 1, but when we create a child it increments the pid by 2. Why is that?
From fork man page :
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.
Fork does not returns the pid of the child, only in the parent. Therefore, the child process does not have two pids.
Try this
int main(int argc, const char * argv[])
{
pid_t thisPid, parentPid, newPid;
int count = 0;
thisPid = getpid();
parentPid = getppid();
printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
if ((newPid = Fork()) == 0) {
count++;
printf("I am teh child. My pid is %d\n", getpid());
exit(0);
}
else
printf("I am the parent. My pid is %d, my child pid is %d\n", thisPid, newPid);
return 0;
}
Pids are one-per process. There will NEVER be more than 1 pid for a process - the internal data structures that handle the process in the OS only have a single PID field in them.
Beyond that, when you call fork() you are cloning the process that called fork, producing an exactly duplicate of it - all file handles, all memory, etc.. EXCEPT for its PID. That's why fork returns different values depending on if you're the child or parent process. This differing return values lets the program know if it's a child or a parent. The child gets 0, and can therefore know it's the child.
No, a pid is assigned to exactly one process at a time.
Process ids do not need to follow any rules when being assigned to processes. So if it looks as if a child pid is the increment of the parent's pid this is just luck.
By the pid of certain processes it is not possible to draw any conclusions regarding the processes relationship.
PIDs are not sequential on assignment (the actually follow no rules) and one process has only one PID at a time. Also there can never be two processes that share the same PID.
I'm starting to learn some C and while studying the fork, wait functions I got to a unexpected output. At least for me.
Is there any way to create only 2 child processes from the parent?
Here my code:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main ()
{
/* Create the pipe */
int fd [2];
pipe(fd);
pid_t pid;
pid_t pidb;
pid = fork ();
pidb = fork ();
if (pid < 0)
{
printf ("Fork Failed\n");
return -1;
}
else if (pid == 0)
{
//printf("I'm the child\n");
}
else
{
//printf("I'm the parent\n");
}
printf("I'm pid %d\n",getpid());
return 0;
}
And Here is my output:
I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766
Please, ignore the pipe part, I haven't gotten that far yet. I'm just trying to create only 2 child processes so I expect 3 "I'm pid ..." outputs only 1 for the parent which I will make wait and 2 child processes that will communicate through a pipe.
Let me know if you see where my error is.
pid = fork (); #1
pidb = fork (); #2
Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.
What you should do is something like this.
if(fork()) # parent
if(fork()) #parent
else # child2
else #child1
After you create process , you should check the return value. if you don't , the seconde fork() will be executed by both the parent process and the child process, so you have four processes.
if you want to create 2 child processes , just :
if (pid = fork()) {
if (pid = fork()) {
;
}
}
You can create n child processes like this:
for (i = 0; i < n; ++i) {
pid = fork();
if (pid > 0) { /* I am the parent, create more children */
continue;
} else if (pid == 0) { /* I am a child, get to work */
break;
} else {
printf("fork error\n");
exit(1);
}
}
When a fork statement is executed by the parent, a child process is created as you'd expect. You could say that the child process also executes the fork statement but returns a 0, the parent, however, returns the pid.
All code after the fork statement is executed by both, the parent and the child.
In your case what was happening was that the first fork statement created a child process. So presently there's one parent, P1, and one child, C1.
Now both P1 and C1 encounter the second fork statement. The parent creates another child (c2) as you'd expect, but even the child, c1 creates a child process (c3). So in effect you have P1, C1, C2 and C3, which is why you got 4 print statement outputs.
A good way to think about this is using trees, with each node representing a process, and the root node is the topmost parent.
you can check the value as
if ( pid < 0 )
process creation unsuccessful
this tells if the child process creation was unsuccessful..
fork returns the process id of the child process if getpid() is used from parent process..
You can create a child process within a child process. This way you can have 2 copies of the original parent process.
int main (void) {
pid_t pid, pid2;
int status;
pid = fork();
if (pid == 0) { //child process
pid2 = fork();
int status2;
if (pid2 == 0) { //child of child process
printf("friends!\n");
}
else {
printf("my ");
fflush(stdout);
wait(&status2);
}
}
else { //parent process
printf("Hello ");
fflush(stdout);
wait(&status);
}
return 0;
}
This prints the following:
Hello my friends!