为什么if和else语句单次执行? [英] Why is it possible that the if and else statements are executed on single run?

查看:224
本文介绍了为什么if和else语句单次执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习套接字编程,并且我很了解c编程.

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

例如,根据我的c语言编程知识,一旦处理else语句内的某些内容,就不应执行相应if语句内的代码.例如,

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;

基于上面的陈述,a等于1,因此应执行process1,而不会执行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

我的问题是,为什么同时显示ifelse语句的结果?

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

推荐答案

Fork用于创建新流程.在旧进程中,它返回新进程的pid,在新进程中,返回0.输出的每一行都是由不同进程打印的.

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

为帮助您理解: 从您调用fork()的那一刻起,又有一个过程正在执行您编写的程序.为了使这两个进程执行不同的操作,fork()在原始进程和重复进程中返回不同的值.如我所写,原始进程收到新进程的pid,这对于两个进程之间的进一步通信非常有用.

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.

这篇关于为什么if和else语句单次执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆