开发者

How to add a pid_t to a string in c

开发者 https://www.devze.com 2023-04-09 15:19 出处:网络
I am experienced in Java but I am very new to C. I am wr开发者_如何学Goiting this on Ubuntu. Say I have:

I am experienced in Java but I am very new to C. I am wr开发者_如何学Goiting 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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消