这是我的代码(只是为了测试 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'
有什么问题吗?
您已获得
#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
,等等)。
正如您已经注意到的,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 库中定义,就不会是一个大问题。只需在兼容性标头中定义您自己的原型,并将标准标头问题报告给维护您的操作系统发行版的人员即可。
只需在Linux虚拟机中运行程序,我的就在那里工作。 Windows 太糟糕了!