[英]How to add a pid_t to a string in 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]
。 我的最終目標不僅僅是打印它。
簡易解決方案
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
。 這不是很難,但你必須了解varargs。 asprintf
非常有用,它應該早在C標准庫中。
編輯 :我最初建議鑄造為long
,但這是不正確的,因為POSIX不保證pid_t
值適合long
。 請改用intmax_t
(包括<stdint.h>
以訪問該類型)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.