에 도달 할 때까지, 나는 다음과 같은 코드가 있습니다포크 오프 이전 마무리로 이상의 프로세스, 최대는 X 프로세스를 포크와 부모가 모두 대기하도록하려면
int maxProcesses = 10;
for (int currentChild = 0; currentChild < maxProcesses; currentChild++) {
pid_t pid = fork();
if (pid < 0) {
// Error
} else if (pid == 0) {
// Child
} else {
// Parent
// Should I call waitpid on pid and wait here instead?
}
}
// Wait for all children
for (int currentChild = 0; currentChild < maxProcesses; currentChild++) {
wait(NULL);
}
지금 내가 코드를 이렇게 수정하고 싶습니다를 X 총 프로세스 수, Y가 먼저 분기 된 다음 끝날 때 원하는 총 수에 도달 할 때까지 더 많은 분기가 이루어집니다. 위의 코드를 약간 변경하고 몇 가지 질문을했습니다.
int totalProcessesToBeForked = 10;
int maxAllowedAtOnce = 5;
for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
forkChild(currentChild);
}
// Wait for all children
// # How do I modify this to wait for new children forked as well
// # if I move it inside parent, it will make things easier, right?
for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
wait(NULL);
}
void forkChild(currentChild) {
pid_t pid = fork();
if (pid < 0) {
// Error
} else if (pid == 0) {
// Child
} else {
// Parent
// # I think waiting here using waitpid will be better b/c
// # as new forks are made, parent begins to wait for them
}
}
은 아마 totalProcessesToBeForked에 갈래되어 얼마나 많은 아이들의 수를 유지하고 비교해야하고 그에 따라 포크 새로운 것입니다.
는업데이트 코드 v1의
int maxProcesses = 10;
int maxAllowedAtOnce = 5;
int main(int argc, char* argv[]) {
// Start timer
alarm(10); // Terminate after 10s
signal(SIGALRM, onTimeout);
signal(SIGCHLD, catchChild);
for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
forkChild(currentChild);
}
// # This sections runs immediately before death of any child is reported
// # and starts cleanup processes, thus killing any/all running children
// Completed before timeout
endTimer = true;
int timeRemaining = alarm(0);
if (timeRemaining > 0) {
printf("\nCompleted w/ %is remaining. Performing cleanup.\n", timeRemaining);
// Kill children any running child processes, cleanup
cleanup();
}
return 0;
}
void forkChild(currentChild) {
pid_t pid = fork();
if (pid < 0) {
// Error
} else if (pid == 0) {
// Child
execl("/bin/date", "date", 0, 0);
} else {
// Parent
printf("#Log: Started %i.\n", currentChild + 1);
}
}
void catchChild(int sig) {
pid_t p;
int state;
p=wait(&state);
printf("Got child %d\n",p);
}
void cleanup() {
// Cleanup Code
}
예 실행 :
편집 # 2 : http://ideone.com/noUs3m
을 확인 이상의 오류를 제외하고, 다음과 같이 귀하의 코멘트 뭔가 대답합니다. 나는 '아이를 얻었다'고 생각하지만 대부분의 경우 정리 후입니다. – Ali
당신의 코드가 단지 아이들을 시작한 다음 정리를하기 때문입니다. 오래된 어린이가 죽을 때 얼마나 많은 어린이가 달리고 새로운 어린이가 태어나는지 지켜 볼 수있는 코드는 없습니다. 'sleep'이있는 while 루프가 시작하기에 좋은 곳이 될 것입니다. –
어디서 잠을 자야합니까? 그리고 어떤 종류의 회 돌이? – Ali