0

I have the following C code.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>


int main ()
{

    int i=1;

    pid_t child_pid = fork();

    if (child_pid == 0) 
    {
        printf ("%d\n", i++);
        printf ("%d\n", i++);
        printf ("This is child process.");
        return 0;


    }
    else if (child_pid > 0) {
        printf ("%d\n", i++);
        printf ("This is parent process.");
    }

    else {
    printf("Fork failed");
    }

}

I compiled the following as follows: gcc testFork.c and ran the code by typing ./a.out.

The output i got was:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ 1
2
This is child process.

Why is vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ appearing in the middle of nowhere?

I am simply expecting this output:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.1
2
This is child process.

2 Answers2

4

Because you didn't add a newline '\n' escape character at the end of your printf call; and thus, when your parent process returned to your shell, the prompt of your shell `vmw_ubuntu@vmwubuntu:~/Desktop/Test C$' was appended to the end.

Remember that when you call 'fork' you're creating 2 separate copies of the same process. It's no longer 1 program, and the parent can return before the child.

EDIT:

To achieve the output you want, you need to insert a call to the 'waitpid' function. see http://linux.die.net/man/2/wait

DeftlyHacked
  • 397
  • 1
  • 9
1

The problem probably is that printf function is buffered: Why does printf not flush after the call unless a newline is in the format string? Disable buffering or use write(..), which is unbuffered. And there is no problem with fork - it works as specified.

Community
  • 1
  • 1
Konstantin K
  • 94
  • 1
  • 8