c - 如果我们首先在 if 或 while 中使用 fork() 为什么会返回双零

标签 c linux

这是我的作业。在代码中,应该有2个进程,父进程和子进程。但在代码中,会有2个零,永远不会进入分支p1>0。 这是一个代码。我使用 fork() 并得到双零,这很令人困惑。我想知道 fork() 在这段代码中是如何工作的。

#include "stdio.h"
#include "unistd.h"
#include "signal.h"
int k1;
void func1(int signo){
    if (signo==SIGUSR2)
    {
        k1=0;
    }

}

int main(int argc, char const *argv[])
{
    int k,p1;
    while (p1=fork()==-1);//one time
    if (p1>0)
    {
        for (k = 1; k < 4; k++)
        {
            printf("parent:pid=%d\n",getpid());
            sleep(1);
        }
        kill(p1,12);
        wait(0);
        printf("OK!\n");
        exit(0);
    }
    else
    {
        signal(12,func1);
        k1=1;
        while (k1==1)
        {
            printf("I'm child\n");
            sleep(1);
        }
        printf("Child forced!\n");
        exit(0);

    }
    return 0;
}

我想知道 fork() 在这段代码中是如何工作的。

代码的输出是循环输出:“我是 child ”。每秒输出两行。

但是,在我看来,应该输出“parent:pid=%d”,但代码不会进入“p1>0”分支。看起来 fork() 生成了 2 个进程,但它们的 p1=0。

最佳答案

问题出在operators precedence , == 的优先级高于 =,因此 while (p1=fork()==-1) 被解析为 while (p1=(fork()==-1))。当您运行此代码时,fork 成功,并且在两个分支中都返回不同于 -1 的值。这就是为什么在子级和父级中,p1 都等于 0(假)。

您需要在赋值周围添加额外的括号:while ((p1=fork())==-1)

关于c - 如果我们首先在 if 或 while 中使用 fork() 为什么会返回双零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56366127/

相关文章:

c - 固定数字的时间复杂度

c - 没有类型的 typedef 是什么意思?

c - 在 C 中编写一个返回 boolean 值的函数

c++ - Linux 中是否有任何 C/C++ 编辑器在键入时显示错误

python - 如何识别频繁启动进程的来源

ruby - 安装 Ruby 脚本 - 初始化错误

c - C 中两个数字求和

c - 编辑 etc\hosts 文件

python - 如何在 Debian Python 中播放声音文件?

c - 是否有调用开发路径的子文件夹的多功能?