In the code below, there is no memory leak in parent and child as far as I checked with valgrind.
Child total heap usage: 1 allocs, 1 frees, 272 bytes allocated
Parent total heap usage: 2 allocs, 2 frees, 1,296 bytes allocated
I have two questions here. First, didn't process allocated memory for create a thread? I didn't join it in the child process. Shouldn't there be memory leak?
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void* foo(void* arg){
puts("hello, world!");
sleep(3);
return NULL;
}
int main(){
pthread_t thread;
pthread_create(&thread, NULL, foo, NULL);
switch(fork()){
case -1:
fprintf(stderr, "error\n");
break;
case 0:
fprintf(stderr, "%d child finished\n", getpid());
break;
default:
pthread_join(thread, NULL);
fprintf(stderr, "%d parent finished\n", getpid());
}
return 0;
}
Second question is, thread isn't existed in the child. But when I changed code like below pthread_join is return 0(success). Shouldn't it return error and set errno in child process?
int main(){
pthread_t thread;
pthread_create(&thread, NULL, foo, NULL);
switch(fork()){
case -1:
fprintf(stderr, "error\n");
break;
case 0:
fprintf(stderr, "%d child finished\n", getpid());
break;
default:
fprintf(stderr, "%d parent finished\n", getpid());
}
printf("%d\n", pthread_join(thread, NULL));
puts(strerror(errno));
return 0;
}