为什么我的编译器不接受 fork(),尽管我包含了 <unistd.h>?

问题描述 投票:0回答:5

这是我的代码(只是为了测试 fork() 而创建):

#include <stdio.h>  
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h> 

int main()
{   
    int pid;     
    pid=fork();

    if (pid==0) {
        printf("I am the child\n");
        printf("my pid=%d\n", getpid());
    }

    return 0;
}

我收到以下警告:

warning: implicit declaration of function 'fork'
undefined reference to 'fork'

有什么问题吗?

c windows mingw fork
5个回答
47
投票

unistd.h
fork
POSIX 标准的一部分。它们在 Windows 上不可用(gcc 命令中的
text.exe
提示您不在 *nix 上)。

看起来您正在使用 gcc 作为 MinGW 的一部分,它确实提供了

unistd.h
标头,但没有实现像
fork
这样的功能。 Cygwin 确实提供了
fork
等功能的实现。

但是,由于这是家庭作业,您应该已经了解如何获得工作环境的说明。


8
投票

您已获得

#include <unistd.h>
,这是声明
fork()
的地方。

因此,您可能需要告诉系统在包含系统标头之前显示 POSIX 定义:

#define _XOPEN_SOURCE 600

如果您认为您的系统大部分符合 POSIX 2008,则可以使用 700,对于较旧的系统甚至可以使用 500。因为

fork()
一直存在,所以它会与其中任何一个一起出现。

如果您使用

-std=c99 --pedantic
进行编译,则 POSIX 的所有声明都将被隐藏,除非您明确请求它们,如图所示。

您还可以使用

_POSIX_C_SOURCE
,但使用
_XOPEN_SOURCE
意味着正确对应的
_POSIX_C_SOURCE
(以及
_POSIX_SOURCE
,等等)。


6
投票

正如您已经注意到的,fork() 应该在 unistd.h 中定义 - 至少根据 Ubuntu 11.10 附带的手册页。最小的:

#include <unistd.h>

int main( int argc, char* argv[])
{
    pid_t procID;

    procID = fork();
    return procID;
}

...在 11.10 上构建时没有任何警告。

说到这里,您使用的是哪个 UNIX/Linux 发行版?例如,我发现一些应该在 Ubuntu 11.10 的标头中定义的不起眼的函数却没有。如:

// string.h
char* strtok_r( char* str, const char* delim, char** saveptr);
char* strdup( const char* const qString);

// stdio.h
int fileno( FILE* stream);

// time.h
int nanosleep( const struct timespec* req, struct timespec* rem);

// unistd.h
int getopt( int argc, char* const argv[], const char* optstring);
extern int opterr;
int usleep( unsigned int usec);

只要它们在您的 C 库中定义,就不会是一个大问题。只需在兼容性标头中定义您自己的原型,并将标准标头问题报告给维护您的操作系统发行版的人员即可。


0
投票

我认为你必须执行以下操作:

pid_t pid = fork();

要了解有关 Linux API 的更多信息,请访问 此在线手册页,或者甚至立即进入终端并键入,

man fork

祝你好运!


0
投票

只需在Linux虚拟机中运行程序,我的就在那里工作。 Windows 太糟糕了!

© www.soinside.com 2019 - 2024. All rights reserved.