C
C#4mo 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
Pobiega4mo 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
MODiX4mo ago
We're partnered with Together C & C++, check them out here: https://discord.gg/vnyVmAE
rho
rho4mo ago
wrong server.. im so sorry lol
Pobiega
Pobiega4mo ago
no worries
rho
rho4mo ago
thanks for letting me know c:
Jimmacle
Jimmacle4mo 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
rho4mo ago
yeah it is
MutableString
MutableString4mo 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