I am not sure what I'm doing wrong.
I'm trying to concatenate hostname
with pid
to create id
.
char *generate_id(void) {
int ret;
char id[1048];
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
sprintf(id, "%s%d", pid);
printf("hostname is %s
", hostname);
printf("The process id is %d
", pid);
printf("The unique id is %s", id);
return id;
}
EDIT:
Updated code after reading some answers:
char *generate_id(void) {
int ret;
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
int size = snprintf(NULL, 0, "%s%d", hostname, pid);
char * id = malloc(size + 1);
printf("hostname is %s
", hostname);
printf("The process id is %d
", pid);
printf("The unique id is %s
", id);
return id;
}
EDIT:
Working code:
char *generate_id(void) {
int ret;
char hostname[1024];
pid_t pid = getpid();
//hostname[1023] = '';
if ((ret = gethostname(hostname,1024) < 0)) {
perror("gethostname");
exit(EXIT_FAILURE);
}
int size = snprintf(NULL, 0, "%s%d", hostname, pid);
char * id = malloc(size + 1);
sprintf(id, "%s%d", hostname, pid);
printf("hostname is %s
", hostname);
printf("The process id is %d
", pid);
printf("The unique id is %s
", id);
return id;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…