0

我有以下代码,我试图一次最多允许 5 个孩子运行,但我不知道如何在孩子退出时减少孩子的数量。

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;
}

修订版似乎可以根据评论工作

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;
}
4

3 回答 3

3

函数族将wait()暂停父进程,直到子进程退出(这样做而不是休眠)。


不,您根本不需要关键部分 - 孩子和父母不共享内存。在默认情况下,您的所有需求都是这样的:

    default:
    {   
        children++;  // Last fork() was successful

        while (children >= 5)
        {
            int status;
            // Wait for one child to exit
            if (wait(&status) == 0)
            {
                children--;
            }
        }

        pid = fork();
    }

(忘记我之前所说的关于初始化children为 1 的内容,我没有注意到children++应该在 while 循环之前)。

于 2010-04-28T12:36:28.570 回答
2

一旦让最初的 5 个子进程运行,您可能希望使用wait()等待子进程完成,此时您可以启动一个新子进程。

于 2010-04-28T12:36:43.187 回答
1

打电话wait()给家长。这将阻塞,直到其中一个孩子退出。

于 2010-04-28T12:36:46.680 回答