如何将pid_t添加到c中的字符串中
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的解决方案:
不是那么容易,但也不是太复杂的解决方案:使用(不可移植的)
asprintf
函数:如果您的平台没有
asprintf
,您可以使用snprintf
:或者根据
snprintf
定义asprintf
。这不是很难,但是你必须理解可变参数。asprintf
非常很有用,它很久以前就应该出现在 C 标准库中了。编辑:我最初建议转换为
long
,但这是不正确的,因为POSIX不保证pid_t
值适合<代码>长。请改用intmax_t
(包含
来访问该类型)。Easy solution:
Not so easy, but also not too complicated solution: use the (non-portable)
asprintf
function:If your platform doesn't have
asprintf
, you can usesnprintf
:or define
asprintf
in terms ofsnprintf
. 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 apid_t
value fits in along
. Use anintmax_t
instead (include<stdint.h>
to get access to that type).