C语言 打印 pid_t 的正确 printf 说明符是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20533606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:30:07  来源:igfitidea点击:

What is the correct printf specifier for printing pid_t

cioprintfpid

提问by Bilal Syed Hussain

I'm currently using a explicit cast to long and using %ldfor printing pid_t, is there a specifier such as %zfor size_tfor pid_t?

我目前使用一个显式的长和使用%ld打印pid_t,有一个符如%z用于size_tpid_t

If not what the best way of printing pid_t?

如果不是最好的打印方式是pid_t什么?

采纳答案by Jim Balter

There's no such specifier. I think what you're doing (casting the pid to longand printing it with "%ld") is fine; you could use an even wider int type, but there's no implementation where pid_tis bigger than longand probably never will be.

没有这样的说明符。我认为你在做什么(将 pid 投射到long并用“%ld”打印)很好;您可以使用更宽的 int 类型,但没有实现pid_t大于long并且可能永远不会的实现。

回答by chux - Reinstate Monica

With integer types lacking a matching format specifier as in the case of pid_t, yet with known sign-ness1, cast to widest matching signed type and print.

对于缺少匹配格式说明符的整数类型,如pid_t,但具有已知符号1,转换为最广泛匹配的有符号类型并打印。

If sign-ness is not known, cast to the widest unsigned type or alternate opinion

如果符号未知,则转换为最宽的无符号类型或替代意见

pid_t pid = foo();

// C99
#include <stdint.h>
printf("pid = %jd\n", (intmax_t) pid);

Or

或者

// C99
#include <stdint.h>
#include <inttypes.h>
printf("pid = %" PRIdMAX "\n", (intmax_t) pid);

Or

或者

// pre-C99
pid_t pid = foo();
printf("pid = %ld\n", (long) pid);


1The pid_tdata type is a signed integertype which is capable of representing a process ID.

1pid_t数据类型是一个带符号的整数,其能够表示进程ID的类型。