0

I've been practicing an exercise in C where I had to create a simple tree of the process. Basically, the main process creates a child process using fork(), then it ends. The child process prints a message, create a child process of its own and it ends too, this procedure iterates 3 times. Well, apparently it's working OK somewhere in the execution I got a weird output (It prints the directory where the executable is). I'm sharing the code and the output from terminal. (Output messages are in Spanish, sorry about that):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


int main(){
    int i;
    pid_t cpid[3];
    printf("¡Hola, soy el proceso padre!\n");
    for (i=0;i<3; i++){
        cpid[i] = fork();
        if (cpid[i] == 0){
            printf("¡Hola, soy el proceso hijo N°%i!\n",i+1);
        }else{
            printf ("Terminando proceso %i....\n",i);
            exit (EXIT_SUCCESS);
        } 
    }
    printf ("Terminando proceso %i....\n",i);
    return 0;
}

And this my output:

fuhranku@frank-ubuntuVB:~/Escritorio/Práctica #1 - Solución/Ejercicios programados$ gcc -o foo ejercicio23.c 
fuhranku@frank-ubuntuVB:~/Escritorio/Práctica #1 - Solución/Ejercicios programados$ ./foo
¡Hola, soy el proceso padre!
Terminando proceso 0....
fuhranku@frank-ubuntuVB:~/Escritorio/Práctica #1 - Solución/Ejercicios programados$ ¡Hola, soy el proceso hijo N°1! <---- WEIRD OUTPUT 
Terminando proceso 1....
¡Hola, soy el proceso hijo N°2!

I don't know why it's showing the directory where the executable file is in the middle of the execution, any idea of the reasons?

Thanks! :-)

Orlandster
  • 4,706
  • 2
  • 30
  • 45
Frank Ponte
  • 135
  • 1
  • 11

1 Answers1

1

You're not waiting for the children processes to end.

So you run your first process, start a whole clan of new processes and exit. When you exit you get back the prompt (which happens to include the current working directory). Then quasi-randomly the other processes you started get a chance to run, print their stuff and exit.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • I have just realized that, it's returning to the prompt because i'm exit the main process, and after it exit the child processes are still up. Thanks! – Frank Ponte Oct 24 '17 at 22:05
  • @FrankPonte Right. Nothing special happens to the children processes just because the parent exits. As a side note, you'll often have an easier time if you use shorter paths without spaces. ("Práctica #1 - Solución" could be "Práctica-1-Solución" for example). – cnicutar Oct 24 '17 at 22:06
  • I'll have that on mind, thanks! – Frank Ponte Oct 24 '17 at 22:19