I have the following code, which I'm trying to only allow a maximum of 5 children to run at a time, but I can't figure out how to decrement the child count when a child exits.
struct {
char *s1;
char *s2;
} s[] = {
{"one", "oneB"},
{"two", "twoB"},
{"three", "thr4eeB"},
{"asdf", "3th43reeB"},
{"asdfasdf", "thr33eeB"},
{"asdfasdfasdf", "thdfdreeB"},
{"af3c3", "thrasdfeeB"},
{"fec33", "threfdeB"},
{NULL, NULL}
};
int main(int argc, char *argv[])
{
int i, im5, children = 0;
int pid = fork();
for (i = 0; s[i].s2; i++)
{
im5 = 0;
switch (pid)
{
case -1:
{
printf("Error\n");
exit(255);
}
case 0:
{
printf("%s -> %s\n", s[i].s1, s[i].s2);
if (i==5) im5 = 1;
printf("%d\n", im5);
sleep(i);
exit(1);
}
default:
{ // Here is where I need to sleep the parent until chilren < 5
// so where do i decrement children so that it gets modified in the parent process?
while(children > 5)
sleep(1);
children++;
pid = fork();
}
}
}
return 1;
}
Revised version seems to work based on comments
struct {
char *s1;
char *s2;
} s[] = {
{"one", "oneB"},
{"two", "twoB"},
{"three", "thr4eeB"},
{"asdf", "3th43reeB"},
{"asdfasdf", "thr33eeB"},
{"asdfasdfasdf", "thdfdreeB"},
{"af3c3", "thrasdfeeB"},
{"fec33", "threfdeB"},
{NULL, NULL}
};
pthread_mutex_t children_count_lock;
int children = 0;
int main(int argc, char *argv[])
{
int i, im5;
int pid = fork();
for (i = 0; s[i].s2; i++)
{
im5 = 0;
switch (pid)
{
case -1:
{
printf("Error\n");
exit(255);
}
case 0:
{
printf("%s -> %s\n", s[i].s1, s[i].s2);
if (i==5) im5 = 1;
printf("%d\n", im5);
sleep(i);
pthread_mutex_lock(&children_count_lock);
children = children - 1;
if (children < 0) children = 0;
pthread_mutex_unlock(&children_count_lock);
exit(1);
}
default:
{
if (children > 4)
wait();
pthread_mutex_lock(&children_count_lock);
children++;
pthread_mutex_unlock(&children_count_lock);
pid = fork();
}
}
}
return 1;
}