Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (fork()) fork()

Tags:

c

fork

I am studying for an OS quiz and I did not understand what output

if(fork())
    fork()

will produce. Can someone explain?

I didn't understand this line:

if(fork())

Edit:

What I meant with "output" is how many processes will be there if this code was executed.

Sorry I'm a bit dizzy after studying.

like image 975
faris Avatar asked Nov 21 '25 04:11

faris


2 Answers

Here's a hint: if (fork()) is just a short way of writing if (fork() != 0).

like image 190
caf Avatar answered Nov 23 '25 21:11

caf


Perhaps you are best off just trying it, reading the documentation for fork, and then, if it still doesn't make sense, asking a more specific question about what part you don't understand.

Start by trying this:

#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv){
    int x,y=0;
    x = fork();
    if (x) y = fork();
    printf("x: %d, y: %d\n",x,y);
    return 0;
}
like image 31
ysth Avatar answered Nov 23 '25 23:11

ysth