Reputation: 253
char *args = "echo hello world";
while(1) {
pid_t pid = fork()
if(pid == 0) {
execlp('sh', 'sh', '-c', args, (char *)NULL);
perror("sh");
return(1);
} else if(pid == -1) {
perror("fork");
return(1);
}
}
I think above would fork bomb. Basically I want it to continuously print out "hello world" to stdout without it fork bombing but still usi ng fork. Is there a way? Basically to watch for a process to terminate then start a new one.
Upvotes: 0
Views: 239
Reputation: 223972
The parent process can pause until the child process is finished by calling wait
:
char *args = "echo hello world";
while(1) {
pid_t pid = fork()
if(pid == 0) {
execlp('sh', 'sh', '-c', args, (char *)NULL);
perror("sh");
return(1);
} else if(pid == -1) {
perror("fork");
return(1);
}
// wait for the child to finish
wait(NULL);
}
You're still looping continuously, but you're not starting a new child process until the prior one finishes.
Upvotes: 3