Reputation: 2448
I am a total beginner in C. I have this assginment to wirte a program that will find the max number of processes I can open.
I come out with this code:
int main() {
while (1){
pid_t pid = fork();
if(pid) {
if ( pid == -1){
fprintf(stderr,"Can't fork,error %d\n",errno);
exit(EXIT_FAILURE);
}else{
int status;
alarm(30);
if(waitpid(pid, &status, 0)==pid) {
alarm(0);
// the child process complete within 30 seconds
printf("Waiting.");
}else {
alarm(0);
// the child process does not complete within 30 seconds
printf("killed");
kill(pid, SIGTERM);
}
}
}
else{
alarm(30);
printf("child");
}
}
}
The thing is this program caused my laptop to crash..:-|
I assumed that when the program will not be able to open more processes I will get -1 from the fork() and then will exit the program. Well, it didn't happened.
Any idea? What am I missing here?
Thanks!
Upvotes: 1
Views: 1394
Reputation: 5400
U cannot "open" a process. You can create them.
CHILD_MAX is a constant that contains the value of max number of child processes that can be created. It is defined in unistd.h header. To query, use the sysconf
function. Pass CHILD_MAX
argument to sysconf
with _SC_
prefix.
#include <stdio.h>
#include <unistd.h>
int main(){
int res = sysconf(_SC_CHILD_MAX);
if (res == -1) {
perror("sysconf");
} else {
printf("The max number of processes that can be created is: %d\n", res);
}
return 0;
}
Upvotes: 1
Reputation: 7798
If you actually want to know how many processes you can open you could use the sysconf call, looking for the _SC_CHILD_MAX variable. Check here.
Upvotes: 2