【问题标题】:How to add a pid_t to a string in c如何将pid_t添加到c中的字符串
【发布时间】:2011-11-27 20:32:38
【问题描述】:

我在 Java 方面经验丰富,但我对 C 语言非常是新手。我在 Ubuntu 上写这篇文章。 说我有:

char *msg1[1028];
pid_t cpid;
cpid = fork();

msg1[1] = " is the child's process id.";

如何连接 msg1[1],以便在我调用时:

printf("Message: %s", msg1[1]);

进程id会显示在“是孩子的进程id”前面吗?

我想将整个字符串存储在msg1[1] 中。我的最终目标不仅仅是打印它。

【问题讨论】:

  • 请使用“格式化代码”工具栏按钮格式化代码。我帮你修好了。

标签: c arrays char fork pid


【解决方案1】:

简单的解决方案:

printf("Message: %jd is the child's process id.", (intmax_t)cpid);

没有那么简单,但也不太复杂的解决方案:使用(非便携式)asprintf 函数:

asprintf(&msg[1], "%jd is the child's process id.", (intmax_t)cpid);
// check if msg[1] is not NULL, handle error if it is

如果你的平台没有asprintf,你可以使用snprintf

const size_t MSGLEN = sizeof(" is the child's process id.") + 10; // arbitrary
msg[1] = malloc(MSGLEN);
// handle error if msg[1] == NULL
if (snprintf(msg[1], MSGLEN, "%jd is the child's process id.", (intmax_t)cpid)
  > MSGLEN)
    // not enough space to hold the PID; unlikely, but possible,
    // so handle the error

或根据snprintf 定义asprintf。这不是很难,但你必须了解可变参数。 asprintf非常很有用,它早在很久以前就应该在 C 标准库中了。

编辑:我最初建议转换为 long,但这不正确,因为 POSIX 不能保证 pid_t 值适合 long。请改用intmax_t(包括<stdint.h> 以访问该类型)。

【讨论】:

  • 我想将它存储在 msg1[1] 中,我的最终目标不仅仅是打印它。
  • 太好了,谢谢伙计!对不起,如果这是一个愚蠢的问题。你太棒了!
  • POSIX 等对pid_t 的大小有何看法?能保证长期适应吗?
  • @asveikau:好点,它实际上没有。唯一安全的选择实际上是将其转换为intmax_t。将其添加到答案中。
  • sizeof("string") 实际上考虑到 nul 终止符,所以(除了任意 10)MSGLEN 是正确的。
猜你喜欢
  • 1970-01-01
  • 2015-03-09
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多