c99 - error: unknown type name ‘pid_t’

c99 - error: unknown type name ‘pid_t’

我正在使用Linux (3.13.0-24-generic #46-Ubuntu),并编写了一个简单的C程序 关于 pid.

编译时遇到一些问题:

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;
}

我用 Google 搜索过;人们似乎在 Windows 上遇到了类似的问题,但我正在使用 Linux。 c99c11 是移除 pid_t 还是移至其他 header?或者……

以下适合我

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

找到了here

在较旧的 Posix 标准中,pid_t 仅在 <sys/types.h> 中定义,但自 Posix.1-2001(第 7 期)以来,它也在 <unistd.h>。但是,为了获得 Posix.1-2001 中的定义,您必须在包含任何标准头文件之前定义适当的 feature test macro

因此以下两个序列中的任何一个都可以工作:

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

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