Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct printf specifier for printing pid_t

Tags:

c

io

printf

pid

I'm currently using a explicit cast to long and using %ld for printing pid_t, is there a specifier such as %z for size_t for pid_t?

If not what the best way of printing pid_t?

like image 443
Bilal Syed Hussain Avatar asked Dec 12 '13 01:12

Bilal Syed Hussain


People also ask

What is the format specifier of pid_t?

There's no such specifier.

What is %z in printf?

We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type.

Which format specifier is used to print the?

It is represented by %o. HexaDecimal Integer Format Specifier (%x) - This Format Specifier is mainly used to print or take input for the Hexadecimal unsigned integer value.

What is the format specifier used to print a string in printf?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character.


2 Answers

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

like image 129
Jim Balter Avatar answered Sep 24 '22 20:09

Jim Balter


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.

If sign-ness is not known for other system type, 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); 

1 The pid_t data type is a signed integer type which is capable of representing a process ID.

like image 41
chux - Reinstate Monica Avatar answered Sep 24 '22 20:09

chux - Reinstate Monica