【问题标题】:Why am I getting an error when using vfork()?为什么我在使用 vfork() 时会出错?
【发布时间】:2010-10-18 09:36:03
【问题描述】:

这是我的代码...我不知道为什么会出现错误段...有人可以向我解释原因吗?

#include <iostream>

#include <string>

// Required by for routine
#include <sys/types.h>
#include <unistd.h>

using namespace std;


int globalVariable = 2;

main()
{
   string sIdentifier;
   int    iStackVariable = 20;

   pid_t pID = vfork();
   if (pID == 0)                // child
   {
      // Code only executed by child process

      sIdentifier = "Child Process: ";
      globalVariable++;
      iStackVariable++;
      cout << "PROCESO NUMERO"<<getpid()<<sIdentifier;
//          printf("Proceso hijo: PID %d - PPID %d\n", getpid(), getppid());
      cout << " Global variable: " << globalVariable;
      cout << " Stack variable: "  << iStackVariable << endl;
      return (0);
    }
    else if (pID < 0)            // failed to fork
    {
        cerr << "Failed to fork" << endl;
        return (1);
        // Throw exception
    }
    else                                   // parent
    {
      // Code only executed by parent process

      sIdentifier = "Parent Process:";
    }

    // executed only by parent

    cout << sIdentifier;
    cout << " Global variable: " << globalVariable;
    cout << " Stack variable: "  << iStackVariable << endl;
    return (0);
}

【问题讨论】:

  • 你需要解决这个问题才能使用代码标签。
  • 如果您在代码之外发布错误,这将有助于识别问题。

标签: c++ operating-system fork


【解决方案1】:

如果你 vfork() 两个进程共享一个地址空间。如果您要立即在子进程中执行另一个进程,您可能应该只使用 vfork() 。创建系统调用的原因是为了避免复制父进程地址空间中的每个页面的开销,只是为了在子 exec 时丢弃所有这些映射。对于您的情况,请改用 fork()。

【讨论】:

    【解决方案2】:

    this 有用吗?请注意有关修改变量的注意事项。

    vfork() 函数与 fork() 具有相同的效果,除了如果由 vfork() 创建的进程修改了用于存储来自 vfork 的返回值的 pid_t 类型的变量以外的任何数据,则行为未定义(),或从调用 vfork() 的函数返回,或在成功调用 _exit() 或 exec 系列函数之一之前调用任何其他函数。

    【讨论】:

      猜你喜欢
      • 2021-03-04
      • 2021-10-02
      • 1970-01-01
      • 2022-01-21
      • 2021-09-10
      • 2019-01-14
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多