C语言 如何将pid_t转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15262315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:35:51  来源:igfitidea点击:

How to convert pid_t to string

cpid

提问by btevfik

So, I need to strcat pid to some string. I have this

所以,我需要将 pid 转换为某个字符串。我有这个

strcat (str,(char*)getpid());

but this doesn't work.

但这不起作用。

----edit----

- - 编辑 - -

ok i understand the downvotes. i was too quick to post a question. and didnt realize pid returns an int and i can't cast an int to char*

好的,我理解downvotes。我太快发表问题了。并没有意识到 pid 返回一个 int 并且我不能将一个 int 转换为 char*

itoa doesnt work because it is not standart c.

itoa 不起作用,因为它不是标准 c。

this is how i did it.

我就是这样做的。

char pid[10];
snprintf(pid, 10,"%d",(int)getpid());
strcat (str, pid); 

回答by nneonneo

Instead of using strcatto build a string, consider using the much more flexible (and efficient!) sprintf/snprintffunction instead:

与其使用strcat构建字符串,不如考虑使用更灵活(更高效!)的sprintf/snprintf函数:

char *end = str;
end += sprintf(end, "%s ", "hello!");
end += sprintf(end, "%ld", (long)getpid());
if(bar)
    end += sprintf(end, "%x", 0xf00d);

Observe that sprintfreturns the number of characters written, so you can build a string without succumbing to Schlemiel the Painter's algorithm. If you want to ensure that you don't overrun a buffer of fixed size, snprintfwill do this for you (strcatwill just blindly concatenate, and there is no standard way to avoid that).

观察sprintf返回写入的字符数,因此您可以构建字符串而不会屈服于Schlemiel the Painter's algorithm。如果您想确保不会超出固定大小的缓冲区,snprintf将为您执行此操作(strcat只会盲目连接,并且没有标准方法可以避免这种情况)。

Note that the pid_tstandardguarantees that there are "one or more programming environments in which the [width] of pid_t... is no greater than the width of type long". Therefore, casting pid_tto longis safe as long as getconfsays so.

请注意,该pid_t标准保证存在“一个或多个编程环境,其中 ... 的 [宽度]pid_t不大于类型的宽度long”。因此,只要这么说,投射pid_tlong是安全的getconf

回答by autistic

I see several references that mention casting to long, and then using the %ldformat specifier of sprintf: sprintf(str + strlen(str), "%ld", (long) getpid());

我看到几个参考文献提到转换为 long,然后使用%ldsprintf的格式说明符:sprintf(str + strlen(str), "%ld", (long) getpid());