C - write() system call prints gibberish instead of pid_t

745 Views Asked by At

The following code:

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

int main()
{
    pid_t mypid = getpid();
    write(1, &mypid, sizeof(pid_t));
    return 0;
}

Prints gibberish instead of actual pid. Why?

1

There are 1 best solutions below

1
On BEST ANSWER

write(.. will not print formatted text, but rather binary output directly to a file descriptor.

Just use printf or fprintf:

fprintf(stdout, "%d", (int) mypid);