Hello!
I'm supposed to write a program forks 3 processes (4 in total, including the father). and then have each process fork three threads and two additional process. These two additional processes will fork three threads as well. You can guess from the unnecessary complexity that this is a class assignment.
Anyway, I wrote the following code that displays a string that tells you what thread that is. For instance, one output should say "I'm thread 2.2.3". Meaning thread 2 from child 2 of process 3 and so on.
My program works for first level threads. But I can't display the threads created by the additional processes. In display mode, the third number is just a random big number, which tells me some kind of address problem.
Here is the code:
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *printme(void* Array){
int *Arr = (int *) Array;
int len = sizeof(Arr) / sizeof(int);
if (len == 1){
printf("I'm thread %d.%d",Arr[0],Arr[1]);
}
else if (len == 2){
printf("I'm thread %d.%d.%d",Arr[0],Arr[1],Arr[2]);
}
printf("\n");
pthread_exit(NULL);
}
void main(){
int i, j, k, l;
int threadLevel1[2];
int threadLevel2[3];
printf("\n");
for (i = 1 ; i < 4 ; i++){ // Loop to fork the three main processes.
if (fork() != 0){
sleep(2);
}
else{
//The newly forked process will create three threads and fork two additional processes.
for (j = 1 ; j < 4 ; j++){
pthread_t *t;
threadLevel1[0] = i;
threadLevel1[1] = j;
if (pthread_create(t, NULL, printme, (void*) threadLevel1) != 0){
perror("pthread_create");
exit(1);
}
}
for (k = 1; k < 3 ; k++){
int a = fork();
if (a != 0){
sleep(2);
}
else if (a == -1){
perror("fork"); /* display error message */
exit(0);
}
else{
for (l = 1 ; l < 4 ; l++){
printf("Coooooooool");
pthread_t *t;
threadLevel2[0] = i;
threadLevel2[1] = k;
threadLevel2[2] = l;
if (pthread_create(t, NULL, printme, (void*) threadLevel2)!= 0) {
perror("pthread_create");
exit(1);
}
}
}
}
}
}
return;
}
PS: The part where is says Cooooool doesn't get displayed. It'll be cool if it did.