-2

关于进程动态池的问题。我需要保留免费进程的信息。如果空闲进程数少于N,我应该创建新进程。但是,我知道free变量在每个过程中都是相同的。如何使free变量“全局”并在子进程中更改会更改父进程中的变量,然后父进程可以检查这一点并制作更多子进程?诸如共享内存和其他 IPC 之类的东西。对他们有点困惑。

 free=5;
 for (i=0;i<5;i++) // create 5 pre-forks
   { 
        pid=fork();
        if (pid==0) //child
        { 
            break;
        }
        else//parent
        { 

        }
    }

    while (1) 
    {
        if (pid==0) // child
        {
             newsock = accept(listensock, NULL,NULL);
             free--; //children is busy
             send(newsock, buffer, nread, 0); 
             close(newsock);
             free++;
        }
        else if (pid>0) // parent
        {
            if ...// if less than n fork() more
        }
    }
4

1 回答 1

0

正如您所说,您可以使用共享内存来存储不同进程之间共享的变量。其中一个进程必须创建该共享内存shmget

shmget 需要一个密钥来识别共享内存区域、大小和一些附加选项。create 的常用选项是IPCCREAT | 0666使用 unix 权限 0666 创建它

其他进程shmget以 0 作为最后一个参数调用以使用已初始化的段。

要将进程方向空间与共享内存连接,您必须使用shmat

例子:

#define KEY ((key_t) 1234)  //Any value, just dont overlap other applications in the machine
#define SIZE sizeof(int)

int* free;

int id = shmget(KEY, SIZE, IPCCREAT | 0666);
if (id < 0) //Error...

free = (int*) shmat(id, 0, 0);
if (free <= (int*)(0)) // shmat failed...

//At this point, you can use free as a normal variable
*free = 5;
*free++;
...
//As various processes can access free, you must use any control mechanism (mutex, semaphores...)

shmdt(id); //Unlink shared memory segment
于 2013-05-01T12:48:32.120 回答