C
C#6mo ago
rho

if(fork) and if(!fork) - how do they work?

Let's say we have the following code:
pid_t pid;
pid = fork();
if(pid == 0) {
if(fork()) printf("A");
else printf("B");
printf("C");
}
else {
if(!fork()) printf("A");
else if (fork()) printf("B");
else printf("C");
}
pid_t pid;
pid = fork();
if(pid == 0) {
if(fork()) printf("A");
else printf("B");
printf("C");
}
else {
if(!fork()) printf("A");
else if (fork()) printf("B");
else printf("C");
}
How many A's, B's and C's are going to be printed? I'm a little bit confused with how fork() works inside "if" and whether I'm in parent or child process.
8 Replies
Pobiega
Pobiega6mo ago
I think you are on the wrong discord my friend this is the C# discord. Your code is... C? C++? regardless, head to $cpp
MODiX
MODiX6mo ago
We're partnered with Together C & C++, check them out here: https://discord.gg/vnyVmAE
rho
rhoOP6mo ago
wrong server.. im so sorry lol
Pobiega
Pobiega6mo ago
no worries
rho
rhoOP6mo ago
thanks for letting me know c:
Jimmacle
Jimmacle6mo ago
assuming c/c++, treating a number as a boolean is false if the number is 0 and true if the number is anything other than 0 so fork() in an if is just checking if the PID is nonzero dunno about inverting it with ! though, that looks weird and i wouldn't do it to begin with is that even valid?
rho
rhoOP6mo ago
yeah it is
HtmlCompiler
HtmlCompiler6mo ago
when you fork() you spawn another process so in father process fork() will return false in child process it will return true (or reverse, i haven't used this stuff in years)
Want results from more Discord servers?
Add your server