tags:

views:

79

answers:

2

I use the functions fork(),exec()...

But how can this program be compiled without including some extra headers (like sys/types.h, sys/wait.h).

I use ubuntu 10.04 with gcc version 4.4.3

#include <stdio.h>
#include <stdlib.h>

int main()
{
 pid_t pid;

 printf("before fork\n");

 pid = fork();

 if(pid == 0)
 {
  /*child*/
  if(execvp("./cpuid", NULL))
  {
   printf("error\n");
   exit(0);
  }
 }
 else
 {
  if(wait(NULL) != -1)
  {
   printf("ok\n");
  }
 }

 return 0;
}
+3  A: 

exec and fork are declared in unistd.h, which is most likely included in one if stdio.h or stdlib.h which you explicitly specified in your code. "wait" is from sys/wait.h though... Try invoking gcc with -c -E to generate a preprocessed output and see where the functions' declarations come from.

bobah
Also, you do get errors if you specify a standard (c89 or c99) rather than the default gcc behaviour.
Pete Kirkham
I haven't used the -E option before, thank you for your advise.
ZhengZhiren
+7  A: 

In C, if you call a function without declaring it the compiler behaves as if the function was implicitly declared to take a fixed-but-unspecified number of arguments and return int. So your code acts as if fork() and execvp() were declared thus:

int fork();
int execvp();

Since execvp() takes a fixed number of arguments and returns int, this declaration is compatible. fork() also takes a fixed number of arguments, but returns pid_t; however since pid_t and int are equivalent types on most Linux architectures, this declaration is effectively compatible too.

The actual definitions of these functions are in the C standard library, which is linked by default, so the definition is available at link time and thus the code works.

caf
Very well said. +1
Jack
Thank you very much. Your answer helps a lot.
ZhengZhiren
What's more, is this gcc behaviour?What about the standard c?
ZhengZhiren
It is standard C behaviour; however it is considered bad practice to write programs that depend upon it (if for no other reason than that it prevents you from declaring the function with a prototype, which means that the compiler cannot check that the number and types of the arguments are correct).
caf