Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pid_t to string

Tags:

c

pid

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

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*

itoa doesnt work because it is not standart c.

this is how i did it.

char pid[10];
snprintf(pid, 10,"%d",(int)getpid());
strcat (str, pid); 
like image 523
btevfik Avatar asked Jan 14 '23 00:01

btevfik


2 Answers

Instead of using strcat to build a string, consider using the much more flexible (and efficient!) sprintf/snprintf function instead:

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

Observe that sprintf returns 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, snprintf will do this for you (strcat will just blindly concatenate, and there is no standard way to avoid that).

Note that the pid_t standard guarantees 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_t to long is safe as long as getconf says so.

like image 98
nneonneo Avatar answered Jan 18 '23 20:01

nneonneo


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

like image 21
autistic Avatar answered Jan 18 '23 21:01

autistic