cunbuffered-output

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


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?


Solution

  • 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);