Why does my compiler not accept fork(), despite my inclusion of ?

前端 未结 4 1361
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 16:48

Here\'s my code (created just to test fork()):

#include   
#include 
#include 
#include 
#inclu         


        
相关标签:
4条回答
  • 2020-12-01 17:02

    As you've already noted, fork() should be defined in unistd.h - at least according to the man pages that come with Ubuntu 11.10. The minimal:

    #include <unistd.h>
    
    int main( int argc, char* argv[])
    {
        pid_t procID;
    
        procID = fork();
        return procID;
    }
    

    ...builds with no warnings on 11.10.

    Speaking of which, what UNIX/Linux distribution are you using? For instance, I've found several non-remarkable functions that should be defined in Ubuntu 11.10's headers aren't. Such as:

    // 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);
    

    As long as they're defined in your C library it won't be a huge problem. Just define your own prototypes in a compatibility header and report the standard header problems to whoever maintains your OS distribution.

    0 讨论(0)
  • 2020-12-01 17:03

    I think that you have to do the following instead:

    pid_t pid = fork();
    

    To learn more about Linux API, go to this online manual page, or even go into your terminal right now and type,

    man fork
    

    Good luck!

    0 讨论(0)
  • 2020-12-01 17:09

    unistd.h and fork are part of the POSIX standard. They aren't available on windows (text.exe in your gcc command hints that's you're not on *nix).

    It looks like you're using gcc as part of MinGW, which does provide the unistd.h header but does not implement functions like fork. Cygwin does provide implementations of functions like fork.

    However, since this is homework you should already have instructions on how to obtain a working environment.

    0 讨论(0)
  • 2020-12-01 17:16

    You have got #include <unistd.h> which is where fork() is declared.

    So, you probably need to tell the system to show the POSIX definitions before you include the system headers:

    #define _XOPEN_SOURCE 600
    

    You can use 700 if you think your system is mostly POSIX 2008 compliant, or even 500 for an older system. Because fork() has been around forever, it will show up with any of those.

    If you are compiling with -std=c99 --pedantic, then all the declarations for POSIX will be hidden unless you explicitly request them as shown.

    You can also play with _POSIX_C_SOURCE, but using _XOPEN_SOURCE implies the correct corresponding _POSIX_C_SOURCE (and _POSIX_SOURCE, and so on).

    0 讨论(0)
提交回复
热议问题