本文介绍了神秘地包含fork()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用fork()演示其工作原理的代码(fork.c).

Here is the code (fork.c) that uses fork() to show how it works.

gcc --version显示gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

#include <stdio.h>
int num = 0;
int main(int argc, char*argv[]){
    int pid;
    pid = fork();       
    if(pid == 0){       /*child*/
        num = 1;
    }else if(pid > 0){  /*parent*/
        num = 2;
    }
    printf("%d", num);
}

然后gcc fork.c -o fork进行编译.它可以编译而没有任何错误,并且可执行文件可以正确运行.但是我没有明确包含头文件unistd.h,还检查了所有递归包含的头文件(gcc -H)

Then gcc fork.c -o fork to compile. It compiles without any error and the executable runs correctly. But I have not included explicitly the header file unistd.h, I have also checked all the recursively included header files (gcc -H)

. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h

然后我在所有文件中都做了grep,但是我没有找到任何fork()声明.

Then I did grep in all the files but I have not found any fork() declaration.

如果从未在任何头文件中声明fork(),它将如何编译而没有任何错误?还是我错过了什么?

推荐答案

在C的较早版本(C99之前的版本:C89或K& R C)中,不需要声明即可调用函数.然后,您有责任提供正确数量和类型的参数,并且假定返回值的类型为int.对于这种情况,编译器不提供任何正确性检查.

In older versions of C (prior to C99: C89 or K&R C) you are not required to have a declaration to call a function. It is then your responsibility to provide correct number and types of arguments, and the return value is assumed to be of type int. Compiler does not provide any correctness checking for this case.

但是,编译器应为此警告您.这就是GCC 6.3所提供的:

Compiler, however, should give you a warning for that. This is what GCC 6.3 gives:

main.cpp: In function 'main':
main.cpp:5:11: warning: implicit declaration of function 'fork' [-Wimplicit-function-declaration]
    pid = fork();
          ^~~~

这篇关于神秘地包含fork()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 09:13