【问题标题】:C - write() system call prints gibberish instead of pid_tC - write() 系统调用打印乱码而不是 pid_t
【发布时间】:2015-12-11 23:22:46
【问题描述】:

以下代码:

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

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

打印乱码而不是实际的 pid。为什么?

【问题讨论】:

  • 因为您没有向stdout 发送文本。 write 是二进制输出函数。试试printf()

标签: c unbuffered-output


【解决方案1】:

write(.. 不会打印格式化文本,而是直接将二进制输出到文件描述符。

只需使用printffprintf

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

【讨论】:

  • 顺便说一下,fprintf 仅在 pid_t 实际上是 signed int 时才有效。施放它可能更安全。
猜你喜欢
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 2020-12-24
  • 2012-10-29
  • 2011-02-04
  • 2014-03-31
相关资源
最近更新 更多