0

I am supposed to work out this code to tell the output for my homework. Could somebody help me out? I'm not looking for the answer but, step by step instructions of how to understand this.

 int main() 
 { 
     int pid; 
     int val = 5; 

     pid = fork(); 

     if (pid == 0) val += 3; 

     if (val == 5) val++; 

     printf(“val=%d\n”, val); 
     exit(0); 
 }
Shahbaz
  • 46,337
  • 19
  • 116
  • 182

2 Answers2

1

The code will print one of the three following options:

val=6
val=8
val=6
val=6
val=8

It depends on which write() syscall completes first: child or parent, and whether the child process is successfully created (it might fail).

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
-1
pid = fork(); 
if (pid == 0) val += 3; 
if (val == 5) val++; 
printf(“val=%d\n”, val);

Case 1: After fork() , parent gets scheduled before the child , and complete's printf() call successfully

    val = 6;         //printed by parent
    val = 8;         //printed by child

Case 2: After fork() , parent gets scheduled before the child , and complete's printf() call successfully

    val = 8;         //printed by child
    val = 6;         //printed by parent

-- Problem with printf() and fork() --

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

int main()
{
    printf("Before forking");
    pid_t pid = fork();

    if (pid == 0)
        printf("child printing");
    else
        printf("parent printing");
}

The output is

term# ./a.out 
Before forkingparent printingBefore forkingchild printing

The problem above is clear that , the statement "Before forking" , is printed twice , where it should have printed only once.

The solution is

  1. Use '\n' , to buffer each line after every printf() call.

  2. As rightly advised here call fflush(0) , to empty all I/O buffers before forking.

Community
  • 1
  • 1
Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39