【问题标题】:c99 - error: unknown type name ‘pid_t’c99 - 错误:未知类型名称“pid_t”
【发布时间】:2015-08-29 02:56:38
【问题描述】:

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

编译时遇到一些问题:

  • gcc pid_test.c,这很好。
  • gcc -std=c99 pid_test.cgcc -std=c11 pid_test.c,给出错误:

错误:未知类型名称“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;
}

我用谷歌搜索过;人们似乎在 Windows 上有类似的问题,但我使用的是 Linux。 c99c11 是否删除 pid_t 或移动到其他标题?或者……

【问题讨论】:

  • 请注意,pid_t 不是标准的 C 数据类型,因此除非您以某种方式启用额外类型,否则它们将不可见。启用它们的一种方法是使用-std=gnu99(或-std=gnu11);另一种是指定要使用的 POSIX 或 X/Open 版本。我通常使用 #define _XOPEN_SOURCE 800(或 700 或 600,具体取决于平台 - POSIX 参见 the compilation environment

标签: c c99 pid c11


【解决方案1】:

以下对我有用

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

【讨论】:

  • 是的,额外的标题#include &lt;sys/types.h&gt; 使它工作。因此,在使用pid_t 以在将来获得兼容性时始终添加该标头似乎是合适的......
【解决方案2】:

在较早的 Posix 标准中,pid_t 仅在 &lt;sys/types.h&gt; 中定义,但从 Posix.1-2001(问题 7)开始,它也在 &lt;unistd.h&gt; 中定义。但是,为了获得 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多