【问题标题】:Beginner problems on pipe, fork and if statement [duplicate]管道,叉子和if语句的初学者问题[重复]
【发布时间】:2013-04-28 10:47:37
【问题描述】:

我正在学习套接字编程,并且对 c 编程非常熟悉。

根据我的 c 编程知识,一旦处理 else 语句中的过程。 if 语句中的进程不应该发生,将被杀死。例如,

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

根据上面的说法,a 等于 1,所以 process1 应该被执行,而 process2 不会被执行。应该是正确的,我希望如此。

我的问题是以下代码

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;
}

我得到了以下输出结果

Processed pid == 0
Processed pid != 0

我的问题是为什么会显示 if 和 else 语句的结果?

【问题讨论】:

    标签: c sockets networking pipe


    【解决方案1】:

    你查过man fork()吗?

    父母获得孩子的PID(非零)并且孩子获得零,因此父母正在运行if的“一侧”,而孩子正在运行“另一侧”。

    当然,返回 -1(返回父级)表示错误。

    【讨论】:

    • 意思是,在我执行了上面的代码之后,两个进程会在fork被调用时分别运行。我说的对吗?
    • 完全正确:就像手册页所说的那样!
    猜你喜欢
    • 1970-01-01
    • 2019-10-31
    • 2022-11-03
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多