pid_t 是否有任何合理的初始/无效值?

Sto*_*row 0 c gcc posix pid default-value

打开-Wextra标志gcc似乎具有禁止structs部分初始化的效果。例如:

// main.c
#include <pthread.h>

typedef struct S {
  int i;
  pid_t pid;
} S;

int main( int argc, char* argv[] ) {
  (void)argc;
  (void)argv;
  S s = { 42 };
  (void)s;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)
$ gcc --version && gcc -Wall -Wextra -pedantic -Werror ./main.c
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

./main.c: In function ‘main’:
./main.c:12:3: error: missing initializer for field ‘pid’ of ‘S {aka struct S}’ [-Werror=missing-field-initializers]
   S s = { 42 };
   ^
./main.c:6:9: note: ‘pid’ declared here
   pid_t pid;
         ^~~
cc1: all warnings being treated as errors
Run Code Online (Sandbox Code Playgroud)

a 是否有任何合理的初始(无效)值pid_t我一直觉得,既然pid_t是不透明的,就不应该对标志值做出任何假设。

如果 a 没有合理的初始/无效值,pid_t 是否还有其他一些好的/广泛使用的编程实践不会遇到此错误?


注意:特别有兴趣了解是否存在不涉及分配任意值的选项,该值在单独的有效性标志变量设置为真之前被假定为无效,例如

typedef struct S {
  int i;
  pid_t pid;
  bool valid;
} S;

S s = { 42, 9, false };
Run Code Online (Sandbox Code Playgroud)

Nat*_*dge 7

pid_t不是完全不透明的,它是由 POSIX ( 2.12.1 )为有符号整数类型,并且有效的进程 ID 始终为正整数 ( 3.300 )。

我将使用0-1作为默认值,因为两者都不是有效的进程 ID。 fork()例如,返回 0 以指示当前进程是父进程,并且-1发生错误。


R..*_*R.. 5

pid_t不透明。零和所有负值都是明确异常的(例如waitpid用于表示要等待的特定进程类别)并且可以说 1 也是异常的,因为 -1 的特殊性阻止了 1 成为您可以正常使用的进程组 ID(传统上,pid 1 是 init 进程)。

就您的目的而言,0 似乎是最合理的选择。