-
Understanding fork()
Here is a simple program which I am running trying to better understand the fork() call.
Code:
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
pid_t pid; //pid values of the parent and child process
pid_t wpid; //return value from waitpid()
char *message;
int n;
int stat;
printf("fork program starting\n");
pid = fork();
if ( (pid=fork()) > 0) { //Parent Process
if( (wpid = waitpid(pid, &stat, 0)) != pid) {
fprintf(stderr, "Signal was received by parent while waiting...Error\n");
fprintf(stderr, "ERRNO: ", strerror(errno));
exit(1);
}
message = "This is the Parent process.";
n = 3;
}
else if (pid == 0) { //Child Process
message = "This is the Child process.";
n =3;
}
else { //Error in Fork Call
fprintf(stderr, "There was an error in the fork call\n");
fprintf(stderr, "ERRNO: %s\n", strerror(errno));
exit(1);
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
exit(0);
}
The output of this program is:
Code:
corey@NuNn-Laptop:~/Desktop/Operating Systems/Test Programs$ ./fork
fork program starting
This is the Child process.
This is the Child process.
This is the Child process.
This is the Child process.
This is the Child process.
This is the Child process.
This is the Parent process.
This is the Parent process.
This is the Parent process.
This is the Parent process.
This is the Parent process.
This is the Parent process.
My question is why when I have 'n=3' does each loop through 6 times?
-
I believe it's 3 times the loop.
and why do you do :
Code:
pid = fork();
if ( (pid=fork()) > 0) {
Isn't one pid = fork() enough?
-
Lol, typo on my part. That fixes my issue, thanks!
Now when I run getppid(), my child's PPID is say 17334. But when I display my parents PID it is 17335, now shouldn't these two numbers match?
-
that's because you're calling fork() twice!
-
Because...
Code:
pid = fork();
if ( (pid=fork()) > 0) {
...you call fork() TWICE.
-
Wow guys, awesome delayed slow-motion response :P. I already said that :P. hehehe
-
cool beans! we're playing follow the leader!
-
-