23

这是我的代码(创建只是为了测试 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'

它有什么问题?

4

4 回答 4

43

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

看起来您正在使用 gcc 作为MinGW的一部分,它确实提供了unistd.h标头,但没有实现类似fork. Cygwin 确实提供了诸如fork.

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

于 2012-03-08T03:14:01.690 回答
7

你已经得到了声明#include <unistd.h>的地方fork()

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

#define _XOPEN_SOURCE 600

如果您认为您的系统主要符合 POSIX 2008,您可以使用 700,对于较旧的系统,甚至可以使用 500。因为fork()一直存在,它会出现在其中任何一个上。

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

您也可以使用_POSIX_C_SOURCE,但 using_XOPEN_SOURCE意味着正确的对应_POSIX_C_SOURCE(和_POSIX_SOURCE,等等)。

于 2012-03-08T03:14:58.390 回答
4

正如您已经注意到的, 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 库中定义的,就不会成为一个大问题。只需在兼容性标头中定义您自己的原型,并将标准标头问题报告给维护您的操作系统分发的任何人。

于 2012-03-08T03:20:16.773 回答
0

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

pid_t pid = fork();

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

man fork

祝你好运!

于 2016-02-02T12:51:22.233 回答