简单的解决方案:
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> 以访问该类型)。