Why is it possible that the if and else statements

2019-03-02 05:59发布

I am learning about socket programming and I know c-programming well.

For example, based on my c-programming knowledge, once something inside an else statement is processed, the code inside the corresponding if statement should not get executed. For instance,

int a = 1;
if(a == 1) process1 ;
else process2;

Based on the statement above, a equals to 1, so process1 should be executed and process2 will not be executed. I believe this is correct.

My question is illustrated with the following code:

int main(void){
   pid_t pid;
   int pp[2];

   pipe(pp);

   pid = fork();
   if(pid == 0){
      printf("Processed pid == 0\n");
   }else{
      printf("Processed pid != 0\n");
   }

   return 0;
}

I get the following output when I run this program:

Processed pid == 0
Processed pid != 0

My question is WHY is the result of both the if and else statement shown?

1条回答
Root(大扎)
2楼-- · 2019-03-02 06:51

Fork is used to create a new process. In the old process it returns the new process's pid and in the new process it returns 0. Each line of the output was printed by a different process.

http://linux.die.net/man/2/fork

To help you understand: From the moment you call fork() one more process is executing the program you wrote. To let you make these two processes do different things, fork() returns different values in the original process and in the duplicate. As I wrote, the original process receives pid of the new process, which is very useful for further communication between the two processes.

查看更多
登录 后发表回答