I'm sure I'm missing something basic, but I'm writing a program that fork()s several child processes, each of which create several pthreads. It seems that the pthread_create call never works from a child process. Here is sample code to explain what I mean:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
// Listen for a request from user proc i
void *wait_for_req(void *cvoid) {
int req;
int read_ret;
printf("new thread started\n");
pthread_exit(NULL);
}
void spawn_read_threads(int proc_num, int n) {
int i;
printf("About to spawn %d read threads\n", n);
for (i=0; i<n; i++) {
pthread_t *t;
printf("spawning new thread\n");
int create_result = pthread_create(t, NULL, wait_for_req, NULL);
printf("_create returned %d\n", create_result);
pthread_join(*t, NULL);
}
}
int main() {
if (!fork())
spawn_read_threads(0, 1);
}
The output of this program is
About to spawn 1 read threads
spawning new thread
But if I comment out if comment out if (!fork())
:
About to spawn 1 read threads
spawning new thread
_create returned 0
new thread started
So why doesn't execution get through create_result in the first case?
And if this is useful:
rob@ubuntu:/mnt/hgfs/Virtual Machines$ uname -a
Linux ubuntu 2.6.32-24-generic #42-Ubuntu SMP Fri Aug 20 14:24:04 UTC 2010 i686 GNU/Linux