Here's my code (created just to test 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; }
I get following warnings:
warning: implicit declaration of function 'fork' undefined reference to 'fork'
What is wrong with it?
In the C and C++ programming languages, unistd. h is the name of the header file that provides access to the POSIX operating system API. It is defined by the POSIX. 1 standard, the base of the Single Unix Specification, and should therefore be available in any POSIX-compliant operating system and compiler.
The fork function is the primitive for creating a process. It is declared in the header file unistd.
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.
The OP has <unistd.h> available; otherwise gcc would have reported a fatal error for the missing header file. MinGW does not implement fork (), you could perhaps try Cygwin (or a real POSIX system) if you really need fork (). Or, you could try a similar windows function. Although Cygwin does implement fork (), it ain't pretty.
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.
with gcc and glibc, the feature test macro isn't actually required for fork. Including unistd.h is enough. The standard does state that applications should define _POSIX_C_SOURCE before including headers though. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With