Recursive Fibonacci using Fork in C (Pt 2) - c

I'm attempting to write a function that recursively computes the resulting fibonacci number from a given int n using forks in C.
Here is the function specification: If doPrint is true, print it. Otherwise, provide it to the parent process. The solution should be recursive and it must fork a new child for each call. Each process should call doFib() exactly once. The method signature cannot be changed. Helper functions cannot be used.
This is a continuation of this question: Recursive Fibonacci using Fork (in C)
Unfortunately, I never figured out a solution to the problem in the last post, however this is my modified code. I thought I had it figured out (psuedo code wise) but came to find out that I still am unsure about a few pieces.
At this point, this is solely for my amusement. This is not homework and won't be covered in my class again (after the most recent test, which has passed).
static pid_t root_pid;
// Function to return exit code for PID
static int exitcode(pid_t pid)
{
pid_t retpid;
int status;
retpid = waitpid(pid, &status, 0);
if (pid != retpid)
{
printf("waitpid error\n");
}
return WEXITSTATUS(status);
}
static void doFib(int n, int doPrint)
{
root_pid = getpid();
pid_t pid1;
int status1;
pid_t pid2;
int status2;
if(n < 2) // Base case, exit back to parent?
{
exit(n);
}
else // if not base case, fork child processes
{
pid1 = fork();
if (pid1 == 0) // Child Process 1 (for fib(n-1))
{
doFib(n-1, doPrint);
exit(n-1);
}
else if (pid1 > 0) // Parent Process
{
pid2 = fork();
if (pid2 == 0) // Child Process 2 (for fib(n-2))
{
doFib(n-2, doPrint);
exit(n-2);
}
// Get value from child process 1
status1 = exitcode(pid1);
// Get value from child process 2
status2 = exitcode(pid2);
// When to print?
if (getpid() == root_pid)
{
int result = status1 + status2;
if (doPrint)
{
printf("%d\n", result);
}
else
{
exit(result);
}
}
}
}
}
A few questions...
Do I need to call both of these functions for each child process?
doFib(n-1, doPrint); exit(n-1);
Is my base case at the beginning correct? (n < 2)
Is my base case at the end correct? (when to print)
Thank you for any help.

The answer for "when to print" really comes down to what you want to print ... if you only want to print the final answer, then you'll most likely need a flag that indicates when you're in the root parent process, and use the if statement to test if you are indeed the root parent so that you only print a single number. If on the other-hand you want to print the entire sequence up to the final number, then an if statement is not needed.
For instance, a good flag value would be the PID of the root process. You could save this in a global variable called root_pid in the first couple lines of main() before you start your forking off of separate child processes. That way all the child processes will have the same value set for root_pid, and the if statement can simply be if (getpid() == root_pid).
So do something like this:
//fib.c
#include <unistd.h>
pid_t root_pid
int main()
{
root_pid = getpid();
//... rest of your program
}
And as mentioned above, make your if statement inside of doFib the following:
if (getpid() == root_pid)
{
//...print results
}
else
{
exit(result)
}

Related

Fork() code not working as expected - Hierarchy making

Good afternoon.
I am currently working on a C program that takes one and only one parameter which designates the number of "child generation"s to be created (the own father counts as 1 already). "wait()" system calls are not to be used for this exercise (the version with "wait" calls happens to work exactly as expected).
For instance, the call $program 4 should generate a hierarchy like this:
Process A creates B
Process B creates C
Process C creates D
The printed messages are not important, as they are merely orientative for the task. With the following code (which happens to work exactly how I want with a "wait()" call) states that all the child processes derive from the same father, which I don't understand why it's happening.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int counter; pid_t result; int i;
/*
We are going to create as many processes as indicated in argv[1] taking into account that the main father already counts as 1!
*/
if (argc > 2 || argc == 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}
int lim = atoi(argv[1]);
//We eliminate the impossible cases
if (lim < 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}
if (lim == 1) {puts("The father himself constitutes a process all by his own, therefore:\n");
printf("Process%d, I'm %d and my father: %d\n", counter, getpid(), getppid());
}
else {
for (i = 0; i < lim; i++) {
result = fork();
if (result < 0) {
printf("Call%d \n", counter); perror("Has failed!");
exit(-1);
}
else if (result) {
break; //Father process
}
else {
counter++; //Child processes increment the counter
printf("Process%d, I am %d and my father: %d\n", counter, getpid(), getppid());
}
}
}
The hierarchy generated by the code above is not the one I expected...
All help is greatly appreciated.
Thank you
With the following code (which happens to work exactly how I want with
a "wait()" call) states that all the child processes derive from the
same father, which I don't understand why it's happening.
I don't see that in my tests, nor do I have any reason to expect that it's actually the case for you. HOWEVER, it might appear to be the case for you if what you see is some or all of the child processes reporting process 1 as their parent. That would happen if their original parent terminates before the child's getppid() call is handled. Processes that are orphaned in that way inherit process 1 as their parent. If the parent wait()s for the child to terminate first then that cannot happen, but if instead the parent terminates very soon after forking the child then that result is entirely plausible.
Here's a variation on your loop that will report the original parent process ID in every case:
pid_t my_pid = getpid();
for (i = 0; i < lim; i++) {
result = fork();
if (result < 0) {
printf("Call%d \n", counter); perror("Has failed!");
exit(-1);
} else if (result) {
break; //Father process
} else {
pid_t ppid = my_pid; // inherited from the parent
my_pid = getpid();
counter++; //Child processes increment the counter
printf("Process%d, I am %d and my father: %d\n", counter, (int) my_pid, (int) ppid);
}
}
You are missing a crucial function call.
for (i = 0; i < lim; i++) {
fflush(stdout); // <============== here
result = fork();
Without it, your fork duplicates parent's stdout buffer into the child process. This is why you are seeing parent process output repeated several times --- its children and grandchildren inherit the output buffer.
Live demo (with fixed formatting for your reading convenience).

Process IDs and fork()

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.

fork() example program. need explanation

this is my code. Please have a look. Can you explain the process flow? it is actually a past paper question. But, I frankly don't understand the concept of fork system calls.
main()
{
int i = 1;
int ret_val= 0;
while(i <= 5)
{
fork();
if(ret_val == 0) /*child code*/
{
printf("in child %d. \n", i);
exit(0);
}
else
{ /*parent code*/
i = i+1;
}
}
}
First of all, in the core image of your program, you initialise two values, ret_val, and i which acts as a counter.
From there on, for 5 times, you fork() the program, creating another process with the same image (code). At this point I am assuming your code is wrong, because you are using the ret_val variable to check if it's the child or parent process, but to do so, you need to assign it the value from fork() like this:
ret_val = fork();
if (ret_val == 0)
// do something as child
else
// parent code here
In essence, your code, for 5 times, increments the value of i and has each child process display the current value of i.

Forking in Linux and the use of setsid()

I have a sample code and I'm at loss in understanding how to figure out what's happening.
I'm only showing relevant parts. The problem is make_daemon().
From what I understand about forking is that code from close(0) onwards is executed by the child which should have a pid == 0.
What happens when the code hits return -1? Does the code return to the parent or does it exit? Does the child p process code execute if(share) in Monitor()?
This code is an extract from Monitor.c in mdadm.
Thanks in advance for any help.
int Monitor( struct mddev_dev *devlist,
char *mailaddr, char *alert_cmd,
struct context *c,
int daemonise, int oneshot,
int dosyslog, char *pidfile, int increments,
int share )
{
if (daemonise) {
int rv = make_daemon(pidfile);
if (rv >= 0)
return rv;
}
if (share)
if (check_one_sharer(c->scan))
return 1;
/* etc .... */
}
static int make_daemon(char *pidfile)
{
int pid = fork();
if (pid > 0) {
if (!pidfile)
printf("%d\n", pid);
else {
FILE *pid_file;
pid_file=fopen(pidfile, "w");
if (!pid_file)
perror("cannot create pid file");
else {
fprintf(pid_file,"%d\n", pid);
fclose(pid_file);
}
}
return 0;
}
if (pid < 0) {
perror("daemonise");
return 1;
}
close(0);
open("/dev/null", O_RDWR);
dup2(0,1);
dup2(0,2);
setsid();
return -1;
}
fork can return three types of return values:
a positive number: this only happens in the parent: it is the pid of a successfully created child.
zero: this is only returned in the child and indicates that this code now executes in the child. This is not the pid of the child, use getpid to obtain the pid of the child.
a negative value (commonly -1). This is also only ever returned in the parent and indicates that fork failed for whatever reason and no child was created.
As to what your code does: yes the child will continue at close(0); provided that a child was indeed created.
When your cild hits return -1 it will return to whatever function called make_daemon back in the parent and will continue execution at that point. Normally forked children would do whatever they are supposed to do and then call exit in order not to mess up what the parent was doing.

Theory,Processes fork()

Goodmorning, i would like to ask 2 things..
1) what returns a fork() did on a child which has already a pid==0 ? if i continue to fork on every son, each of them will have 0 as pid ?? or not ?
2) this is my file Buffer.c and it runs on a single process.
At the beginning it forks() out some Producers who produce() and some Consumers who consume() ,but I am afraid that every producers enters in the next for cicle and it starts to produce himself other consumers!! because it write pid=-1 so...
I want that this piece of code produce only P producers and C consumers, but i need to know why every producer do not create other consumers!
Can you help me,maybe giving me a scheme of how many processes i will create with this code?
Maybe doing a scheme as this:
Father:
8 producers
-
-
-
...
each of them produces: 5 consumers
etc etc......
int main(int argc, char **argv) {
/....
pid_t pid;
pid_t cons_pid[C];
/* fork producers */
pid = -1;
for(i=0; i<P && pid!=0; i++)
pid=fork();
switch(pid) {
case -1:
...
case 0:
/* GENERIC PRODUCER i */
...
/* PRODUCE() */
printf("Producer %d exits\n",i);
...
return 0;
}
/* fork consumers */
pid = -1;
for (j=0; j<C && pid!=0; j++)
pid = cons_pid[j] = fork();
switch(pid) {
case -1:
....error
case 0:
/* GENERIC CONSUMER j */
CONSUME()....
}
return 0;
}
what returns a fork() did on a child which has already a pid==0
0 is not a valid PID, hence by definition there can't be an process with PID=0 and thus PID=0 is a perfectly well defined return for indicating child status.
if i continue to fork on every son, each of them will have 0 as pid
No process ever has PID=0. All PIDs are greater than zero! A zero is just the return value received by the newly forked process to indicate that it's the child. The actual PID a child process got is queried using the getpid function from the child process. However the parent process can't perform such a query, since in the time between fork and a assumed query function call, the child may already have terminated (race condition). So you want fork to return the PID to the parent directly.
BTW: The terminology is parent and child not father and son (processes are things not people, despite what the TRON movies depict).
Regarding your code snippet: A switch statement is the wrong choice here. You want to use an if statement.
fork() splits up the current process into a father and a child. The child will have a new PID, the father retains the old PID. In both processes fork() returns after the splitting. In the father the return value will be the PID of the child (to make it known), and in the child the return value will be 0.
1) The lowest possible process ID is 1, this is the ID of the init process from which all other processes are forked. Therefore, it is not possible for a child or for your parent process to "already have ID 0". Your child's process ID is necessarily greater than 1. Thus, the problem that you are afraid of cannot happen.
2) The confusion that you state is the reason why fork (which returns twice, once for the parent and once for the newly created child!) has a somewhat "weird" return value which can have so many different values:
it can be -1, then something went wrong, and no child was created.
it can be a positive value, then you are in the parent process, and the value is the child's process ID. It's as if you called any other "normal" function that just returned normally.
it can be 0, then your code knows it is now running in the child process.
You must examine the return value (if()) so you know what process you are in. Then no such thing as you decribe can happen (or, should happen, this presumes your code does not have any bugs).
EDIT:
The code can be rewritten slightly so it gets rid of the && pid!=0 inside the loop and thus looks a bit less scary overall:
int main()
{
int pid, i;
pid_t cons_pid[C];
for(int i=0; i<P; ++i)
{
pid=fork();
if(pid == -1) exit(1); /* fork error */
if(pid == 0) { producer(); return 0; }
}
for(i=0; i<C; ++i)
{
pid = fork();
if(pid == -1) /* fork error */
{ /* should do a kill_producers(); here */ exit(2); }
else if(pid == 0) /* consumer */
{ consumer(); return 0; }
else /* master process, remember all consumer pids */
{ cons_pid[j] = pid; }
}
/* ... */
return 0;
}

Resources