如何将pid_t添加到c中的字符串中

发布于 2024-12-07 03:20:36 字数 368 浏览 1 评论 0原文

我在 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] 中。我的最终目标不仅仅是打印它。

I am experienced in Java but I am very new to C. I am writing this on Ubuntu.
Say I have:

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

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

How can I concatenate msg1[1] in such a way that when I call:

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

The process id will be displayed in front of " is the child's process id."?

I want to store the whole string in msg1[1]. My ultimate goal isn't just to print it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿看小鸭子会跑 2024-12-14 03:20:36

简单的解决方案:

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值适合<代码>长。请改用 intmax_t(包含 来访问该类型)。

Easy solution:

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

Not so easy, but also not too complicated solution: use the (non-portable) asprintf function:

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

If your platform doesn't have asprintf, you can use 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

or define asprintf in terms of snprintf. It's not very hard, but you have to understand varargs. asprintf is very useful to have and it should have been in the C standard library ages ago.

EDIT: I originally advised casting to long, but this isn't correct since POSIX doesn't guarantee that a pid_t value fits in a long. Use an intmax_t instead (include <stdint.h> to get access to that type).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文