为什么出现错误:“fork”未在此范围内声明?

问题描述 投票:0回答:1
#include <iostream>
#include <unistd.h>
using namespace std;

int main()
{
    
    int fd[2];
    //fd[0] - read
    //fd[1] -write
    //declare all the variables
    int n;
    int countN;
    int arr[3];
    //prompt for the numbers called n
    //there are at most 3 nums(use countN to check)
    while(countN <= 2){
        cin >> n;
        // checked whether the num is from range 1 to 15
        if(n >= 1 && n <= 15)
        {
        //if yes, then push the num to array called arr
          arr[countN] = n;
          countN++;
        }
        else
        {
            //if no, then only increase the countN so that we dont cin more than 3 nums
            countN++;
        }
    }

    //print all the nums in the array named arr
    for(int i = 0; i < 3; i++)
    {
        cout << arr[i];
    }

    //initializes fork
    pid_t c_pid = fork();
    //everything belows this gonna gets executed twice

    return 0;
}

因此,我尝试初始化 fork 系统调用,但出现错误:

在函数“int main()”中:“fork”未在此范围内声明。有人可以告诉我我做错了什么,因为我已经检查以确保 fork 初始化不在 if 或 while 循环等任何块内。

我什至尝试在代码的第一行(main()之后)声明它,但它仍然有这个错误。

pipe fork
1个回答
0
投票

我怀疑您正在 Windows 上进行编译,可能使用 MinGWMingw-w64 ,因为您的错误消息的措辞与 GCC 的措辞方式相同。 Windows 没有

fork()
。您的选择基本上如下:

  1. 重写你的程序以不使用
    fork()
  2. 使用兼容层(如 CygwinMSYSMSYS2
  3. )编译程序
  4. 在不同的操作系统(例如 Linux)上编译您的程序(您可以使用 WSL 或虚拟机)
© www.soinside.com 2019 - 2024. All rights reserved.