0

When I run the code bellow it gave me a strange output

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

int main (int argc, char ** argv)
{
    int pid1, pid2;
    if ((pid1=fork())<0)
    {
        printf("Error\n");
        exit(1);
    }
    if (pid1=!0)
        printf("A\n");
    printf("B %d", getpid());
    if ((pid2=fork())<0)
    {
        printf("Error\n");
        exit(2);
    }
        printf("A\n");
        return 0; 
}

It should be something like

A
A
BA
BA
A
A

But instead the output is

A
A
BA
BA
BA
BA

And I don't know why. Any advice or explanation pls.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 4
    You should see at least `%d", getpid()` some number in the output. Are you sure you are running the program you copied here? – KamilCuk Jan 21 '21 at 14:28
  • `fork()` returns `pid_t` not `int`. – alk Jan 21 '21 at 14:30
  • 1
    The getpid() was added later to see the pid ID. – Petrica Vladovici Jan 21 '21 at 14:31
  • 3
    You have `if (pid1=!0)` which is quite different from `if (pid1 != 0)` — yours is an assignment of `1` to `pid1`, which always evaluates to true. – Jonathan Leffler Jan 21 '21 at 14:33
  • Your sample outputs don't include the PID which `printf("B %d", getpid());` prints. That's mildly puzzling. – Jonathan Leffler Jan 21 '21 at 14:34
  • @JonathanLeffler it was added later as OP states. This is a true duplicate of the "printf anomaly after fork" – Antti Haapala -- Слава Україні Jan 21 '21 at 14:36
  • You should consult [`printf()` anomaly after `fork()`](https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork) for a discussion of the problems/effects caused by `printf("B %d", getpid());` without a newline forcing the output. – Jonathan Leffler Jan 21 '21 at 14:37
  • Add `fflush(stdout);` just before the second `fork()` to fix it. – Ian Abbott Jan 21 '21 at 14:38
  • @IanAbbott I want to know why it's happen that issue more then how to solve it. A \n solve the issue. – Petrica Vladovici Jan 21 '21 at 14:47
  • 1
    The answers to the duplicate question explain what's happening. After the `fork()`, the state of the standard I/O stream buffers is the same in both the parent and child processes, so if the output (and input) stream buffers are not empty, their contents are duplicated. – Ian Abbott Jan 21 '21 at 14:53
  • Appending a `\n` to `B` will not always solve the problem. Try redirecting the output to a file or piping it through `cat` and the problem will return because `stdout` will be fully buffered instead of line buffered. – Ian Abbott Jan 21 '21 at 14:57

0 Answers0