[Error] 'fork' was not declared in this scope

进程互斥实验
头文件已包含该函数,但是编译时仍然报错
之前也是这么写的但是没有报错
代码

#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
    pid_t pid1=-1;
    pid1=fork();
    if(pid1>0)
    {
        pid_t pid2=fork();
    if(pid2<0)
    {
        cout<<"perror"<<endl;
    }
    if(pid2>0)
    {
        lockf(1,1,1);
        int son ,father;
        son=getpid();
        father=getppid();
        cout<<"father pid:"<<son<<""<<"其父进程 pid:"<<father<<endl;
        for(int i=1;i<=10;i++) 
        {
            cout<<"father"<<i<<endl;
            sleep(3);
        }
        lockf(1,0,1);
    }
    if(pid2==0)
    {
        lockf(1,1,1);
        int son ,father;
        son=getpid();
        father=getppid();
        cout<<"son pid:"<<son<<" "<<"其父进程 pid:"<<father<<endl;
        for(int i=1;i<=10;i++)
        {
            cout<<"son "<<i<<endl;
            sleep(4);
        }
        lockf(1,0,1);
    }
    }
if(pid1==0)
{
    lockf(1,1,1);
    int son ,father;
    son=getpid(); 
    father=getppid();
    cout<<"daughter pid:"<<son<<""<<"其父进程 pid:"<<father<<endl;
    for(int i=1;i<=10;i++)
    {
        cout<<"daughter "<<i<<endl;
        sleep(5);
    }
    lockf(1,0,1);
}
}

img

img

方案来自 梦想橡皮擦 狂飙组基于 GPT 编写的 “程秘”


  • 这个错误提示表明在当前的作用域中,编译器找不到名为“fork”的函数或变量的定义。

  • 这可能是由于头文件包含有误或者编译器环境发生变化导致的。

  • 建议确认头文件是否正确包含并且确保编译器环境没有发生变化,如修改了编译器版本或编译选项等。

  • 另外,如果您使用的是C++编译器,还需要确认头文件是否使用了C++语法,如需要在头文件包含处添加extern "C"来指定使用C语言语法。

可以看看代码是怎么写的吗,这个感觉有些看不出来问题啊