C 编程 vfork 返回值

标签 c fork

我必须创建一个程序:

  • 索要电话号码
  • 创建子进程(使用 vfork)
  • 计算平方根(在子进程中)
  • 显示父进程的平方根

这是我的代码

#include <stdio.h>
#include <sys/types.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    double n=0;
    printf("Number: "); //ask number
    scanf("%d", &n);

    pid_t pid = vfork(); //create child process

    if (pid==0)//if child process
    {
        printf("Child process started\n");
        n = sqrt(n);//calculate square root
    }
    else//parent process
    {
        printf("Returnning to parent process\n");
    printf("Square Root: %d",n);
    }       

    return 0;
}

但是我的代码不起作用,有人可以帮助我吗?

最佳答案

为什么你会期望它能起作用?在 vfork 之后执行除 exec_exit 以外的任何操作都会导致显式未定义的行为。请参阅:

vfork() system call

以及对 vfork 的恐怖之处的进一步讨论:

http://ewontfix.com/7/

http://www.openwall.com/lists/musl/2012/12/31/16

如果你感兴趣的话,这里列出了你的程序可能出现的问题(UB 的表现):

    子级中的
  • printf 可能会严重破坏父级的 stdio 状态。
  • n 可以永久存储在寄存器中,在这种情况下,父级无法看到子级所做的更改
  • 编译器可以看到nelse分支中未初始化,因此它根本不需要生成任何代码来读取它(该分支通过访问无条件调用UB其值不确定的对象)。

关于C 编程 vfork 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607061/

相关文章:

c - fork() 在 gcc 编译器中如何运行?

c - for 循环内出现 fork,进程过多

c - 如何使用 2 个应用程序同时连接两个智能卡读卡器

linux - clone/fork/vfork后父子进程返回地址不同

c++ - 如果我被冒充,为什么 Win32 API 函数 CredEnumerate() 会返回 ERROR_NOT_FOUND?

c - 我的程序不会按条件停止

c++ - 我如何等待子进程结束

fork - 我如何 fork 币安智能链并创建自己的区 block 链

c - undefined reference /未解析的外部符号

c - 数组 C 的动态内存分配