-3

I am having error with my code below

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

int main()
{
        int i, status;
        pid_t child;
        child=fork();
        if(child == 0){
        for(i=0; i<10; i++){
            printf("\tChild PID = %d\n", getpid());
            printf("\tChild PPID = %d\n", getppid());
            sleep(1);
        }
        exit(0);
        }
        else{
        for(i=0; i<10; i++){
            printf("Parent PID = %d\n", getpid());
            printf("Parent PPID = %d\n", getppid());
        }
        }
        waitpid(child, &status, 0);
        return 0;
}

I code in GCC(Unix) , and get the following error :

test.c:27:1: error: expected identifier '(' before '}' token

Can someone suggest me any help? Thanks in advance :)

adadeh
  • 185
  • 1
  • 1
  • 7

1 Answers1

2

The man page for waitpid() states:

#include <sys/types.h>
#include <sys/wait.h>

Anyway, the error might due to the usage of pid_t which is defined in sys/types.h.

Using -Wall to turn on all compiler warnings would have pointed one to the missing prototype of waitpid().

Update: This assumes Linux.

alk
  • 69,737
  • 10
  • 105
  • 255
  • What man page? Some don't mention `sys/types.h`. –  Oct 07 '12 at 17:51
  • i try gcc -Wall test.c and the output are: test.c: in function 'main': test.c:8:2: warning: implicit declaration of function 'fork' – adadeh Oct 07 '12 at 17:53
  • @VladLazarenko: `This page is part of release 3.27 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.` Please excuse assuming the OP refers to Linux. – alk Oct 07 '12 at 17:54
  • You might like to check your local man-pages for `fork()` or scan the appropriate header files for which declares it and the other functions (`waitpid()`, `sleep()`) you are using and trhen `#include` such file(s) into your sources. @adadeh – alk Oct 07 '12 at 18:02
  • @alk searching manually for the headers isnt it? Ok – adadeh Oct 07 '12 at 18:42