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

int main()
{
    //fork();
    //printf("Hello World\n");
    int i=fork();
        // child process because return value zero
    if (i == 0)
        printf("Hello from Child! %d \n",i);
 
    // parent process because return value non-zero.
    if (i!=0)
        printf("Hello from Parent! %d \n",i);

    return 0;
}

Why the first output is giving two print output while other are only giving outputs from the Parent Only - when fork() creates two processes.

I am expecting two output print in each output case because of the existence of two process.

Can anyone explain why ?

Output 1:

Hello from Parent! 600 
Hello from Child! 0 

Output 2:

Hello from Parent! 8206 

Output 3:

Hello from Parent! 350 

Output 4:

Hello from Parent! 1098 

Why the first output is giving two print output while other are only giving single outputs from the Parent Only - when fork() creates two processes. I am expecting two output print in output case.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Vivek
  • 1
  • 3

2 Answers2

1

Make sure the child process is successfully terminated. You can run additional code to ensure the child process is terminated before the parent process.

int pid = fork();
//...............
kill(pid, SIGKILL);

EDIT: See this answer: How to kill child of fork?

Vahan
  • 166
  • 13
  • How would doing this change whatever string the child process prints? Outside of killing it before it printed anything? – Andrew Henle Mar 13 '23 at 11:26
  • I figured any call to fork() after the first child process is created will not create a new process, since an identical child process is already running. Killing the child process before exiting parent process would ensure that won't happen. – Vahan Mar 13 '23 at 11:29
0

Given this code

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

int main()
{
    //fork();
    //printf("Hello World\n");
    int i=fork();
        // child process because return value zero
    if (i == 0)
        printf("Hello from Child! %d \n",i);
 
    // parent process because return value non-zero.
    if (i!=0)
        printf("Hello from Parent! %d \n",i);

    return 0;
}

if fork() were to fail, it would generate the output you're seeing.

This code will tell you why fork() fails:

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

int main()
{
    //fork();
    //printf("Hello World\n");
    pid_t i=fork();
    if (i < 0)
        perror( "fork() failed" );
        // child process because return value zero
    if (i == 0)
        printf("Hello from Child! %d \n",( int ) i);
 
    // parent process because return value non-zero.
    if (i!=0)
        printf("Hello from Parent! %d \n", ( int ) i);

    return 0;
}

Also, note that fork() returns pid_t, not int. They don't have to be the same.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56