c99 - error: unknown type name ‘pid_t’

25,219

Solution 1

The following works for me

// getpid() & getppid() test
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>    //NOTE: Added
int pid_test() {
    pid_t pid, ppid;
    pid = getpid();
    ppid = getppid();
    printf("pid: %d, ppid: %d\n", pid, ppid);
    return 0;
}

int main(int argc, void *argv[]) {
    pid_test();
    return 0;
}

I found it here

Solution 2

In older Posix standards, pid_t was only defined in <sys/types.h>, but since Posix.1-2001 (Issue 7) it is also in <unistd.h>. However, in order to get definitions in Posix.1-2001, you must define an appropriate feature test macro before including any standard header file.

So either of the following two sequences will work:

// You could use an earlier version number here;
// 700 corresponds to Posix 2008 with XSI extensions
#define _XOPEN_SOURCE 700
#include <unistd.h>

or

#include <sys/types.h>
#include <unistd.h>
Share:
25,219
Eric
Author by

Eric

while(fail) { pivot(); trial(); } while(succeed) { repeat(); improve(); }

Updated on August 29, 2020

Comments

  • Eric
    Eric almost 4 years

    I am using Linux (3.13.0-24-generic #46-Ubuntu), and wrote a simple C program about pid.

    When compile, I got some issue:

    • gcc pid_test.c, this is fine.
    • gcc -std=c99 pid_test.c or gcc -std=c11 pid_test.c, gives error:

    error: unknown type name ‘pid_t’

    pid_test.c:

    // getpid() & getppid() test
    #include <stdio.h>
    #include <unistd.h>
    
    int pid_test() {
        pid_t pid, ppid;
        pid = getpid();
        ppid = getppid();
        printf("pid: %d, ppid: %d\n", pid, ppid);
        return 0;
    }
    
    int main(int argc, void *argv[]) {
        pid_test();
        return 0;
    }
    

    I did search with Google; people seem have similar issue on Windows, but I am using Linux. Does c99 or c11 remove pid_t or move to other header? Or…

    • Jonathan Leffler
      Jonathan Leffler almost 9 years
      Note that pid_t is not a standard C data type, so unless you enable extra types somehow, they won't be visible. One way to enable them is to use -std=gnu99 (or -std=gnu11); another is to specify a POSIX or X/Open version to use. I usually use #define _XOPEN_SOURCE 800 (or 700 or 600, depending on platform — see the compilation environment for POSIX.
  • Eric
    Eric almost 9 years
    Yes, the additional header #include <sys/types.h> makes it work. So, it seems proper to always add that header when use pid_t to get compatibility in future ...