Reputation: 95
Today, I wrote a small program in C++ like this:
pid_t pChild=0;
printf("Main process ID:%d\n",getpid());
pChild= fork();
printf("%d\n",pChild);
if (pChild!=0){
printf("Parent process ID:%d\n",getpid());
printf("Child process ID:%d\n",pChild);
}
else printf("Sorry! The child can not be created\n");
return 0;
And the output was like this
Main process ID: 3140
Sorry! The child can not be created
Parent process ID:3140
Child process ID:3141
And then, I wondered about the output.
I guessed the first getpid() of the child process didn't run because it read the same data with the getpid() from its parent; and this msg
Sorry! The child can not be created
It must be from the if statement of the child process. Correct me if I wrong...
But I still can't understand why the fork() function of the child's didn't run. Why it was blocked? Does it because they read the same pChild data (one of the fork() in child process and the other is main process's if-statement)?
Can anyone explain more detail about it? Thank you.
Upvotes: 1
Views: 1131
Reputation: 1
From the fork()
documentation:
RETURN VALUE
Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process.
Your code assumes any zero return value is an error.
Continuing:
Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.
A -1
return value is an error indication.
Upvotes: 5