Here is what I have:
struct test_date {
time_t t;
pid_t pid;
};
int main(int argc, char *argv[]) {
dates = malloc(CHILDREN_LIMIT * sizeof(struct test_date*)); // an array declared static of type struct test_date
//... later
struct test_date *td = &dates[children]; //children is a counter
if (fork() == 0) { // in a child process
td->pid = getpid();
time(&(td->t));
//now, if I print the date, I get a strange result. look bellow for get_time function.
printf("%s\n", get_time(&td->t));
//...
}
//...
exit(0);
}
char *get_time(time_t *t) {
struct tm *bt = malloc(sizeof(struct tm*));
char *strt = malloc(DATE_SIZE * sizeof(char *));
localtime_r(t, bt);
strftime(strt, 100, "%Y-%m-%d %T", bt);
return strt;
}
The output for this code:
eg. It should be: 2013-07-16 09:21:28
But it is: 2013-858861619-16 09:21:28
Even more, if I call the same printf
function later, in some functions called from child process, I get an even worse result. A date somewhere to 1974.
Can anybody tell me where is my mistake? I guess it should be where I pass the time_t
variable as pointer, but I can't understand why this behavior. Can anybody detail on this topic?