1

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?

alk
  • 69,737
  • 10
  • 105
  • 255
qiubit
  • 4,708
  • 6
  • 23
  • 37

1 Answers1

5

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);
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175