-1

i have a question that tells me to write the output of the following program :

cont = 0; int p[2];

void* f1() {    
    while(!cont){} 
    printf("%d ", close(p[0])); return NULL; 
}

int main() { 
    pthread_t t1;

    pipe(p); 
    pthread_create(&t1,NULL,f1,NULL);
    fork(); 
    printf("%d ", close(p[0]));
    cont = 1;   
    pthread_join(t1,NULL); 

    return 0;
}

the answer is 2 options : either 0 -1 0 or 0 0 -1

i think the answer is 0 -1 0 -1 , since everything is duplicated using fork() this means that the parent will call close(p[0]) and print 0 and then its duplication of the thread will call close(p[0]) but print -1 , and the same happens with the child. so overall 0 -1 0 -1 , what did i do wrong ?

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    Did you run it to see what you get? – kaylum Jul 10 '22 at 22:41
  • You should read up on how fork and threads interact... – Shawn Jul 10 '22 at 22:55
  • 2
    "*its duplication of the thread*". `fork` does not result in all the parent process threads being run in the child process. From the [fork manual](https://manpages.org/fork): "*A process shall be created with a single thread*" – kaylum Jul 10 '22 at 22:58
  • 1
    What a terrible question. I suppose it is intended at least in part to probe your understanding of the point that @kaylum raised, but the program has a data race involving `cont`, and therefore its behavior is undefined. – John Bollinger Jul 10 '22 at 23:16
  • Additionally, even if the data race were fixed (by making `cont` atomic, for instance), it is unspecified in what relative order the outputs from the two resulting processes will be written. Either "0 0 -1" could be produced (two ways) or 0 -1 0 could be produced. – John Bollinger Jul 10 '22 at 23:21
  • 1
    (To be clear: I am primarily criticizing the question posed to you, not the one you have posed to us.) – John Bollinger Jul 10 '22 at 23:25
  • regrding: `while(!cont){} ` tjhis produced a loop that will never exit so the following call to printf(0 and close() will never be executed – user3629249 Jul 12 '22 at 15:38
  • rhis `fork(); printf("%d ", close(p[0])); cont = 1; pthread_join(t1,NULL);` is being executed in both the parent and the child process which process executes a `printf()` first is totally arbitrary – user3629249 Jul 12 '22 at 15:44

1 Answers1

0

Here are good answers about what happens when a process using pthread uses fork.
This should explain why only 3 outputs are displayed from printfs.

BenYoo
  • 116
  • 5