Process/childrens

Yannick's Avatar, Join Date: Sep 2008
Newbie Member
Hi, with a "Father" process i want to create 3 children process, i tryed to use that code but i think that is wrong cause i see that in my code "Father create" the children1 process next children1 create a children2 process, they are all not from the "Father" process...Anyone can help me?

Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

int main(){
	
	int filho1,filho2,filho3;

	filho1 = fork();
	if (filho1 == 0){
		printf("[%d] Sou o filho1!\n", getpid());
		printf("[%d] O meu pai é: %d\n", getpid(), getppid());
	}

	filho2 = fork();
	if (filho2 == 0){
		printf("[%d] Sou o filho2!\n", getpid());
		printf("[%d] O meu pai é: %d\n", getpid(), getppid());
	}

	filho3 = fork();
	if (filho3 == 0){
		printf("[%d] Sou o filho3!\n", getpid());
		printf("[%d] O meu pai é: %d\n", getpid(), getppid());
	}

	return 0;
}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
What happens if, say, filho1 != 0?
teacher's Avatar, Join Date: Mar 2011
Contributor
sorry for late reply but i think many guys faces this problem..

so just put exit(EXIT_SUCCESS) in each if block at the end.

so each process will get terminated after doing its job.

do not forget to include header file <stdlib.h>

like for eg
Code: cpp
if (filho1 == 0){
        printf("[%d] Sou o filho1!\n", getpid());
        printf("[%d] O meu pai é: %d\n", getpid(), getppid());
exit(EXIT_SUCCESS)
}