Click to See Complete Forum and Search --> : Problem with fork() and execv()


bleakcabal
03-01-2004, 11:32 AM
I have a program that must call execv with a command entered by the user. If I just call execv the program works but quits after execv, which I think is normal from reading man:execv. So I decided to create a child process like this ( this is in a loop ):

pid = fork();
if (pid == -1) {
printf("\nError");
}
else if (pid == 0) {
wait(NULL);
execv(myStrCat("/bin/", cmd[0]), cmd);
}


The problem is sometimes, and I can't find a pattern for this, the program just goes into an infinite loop where it creates child processes so fast that I can't do anything about it. And these process do not execv anything they just do nothing ( maybe it is because execv executes cmd which must be inputed by the user ). This goes on until :
1: the max number of process that I am able to create under /etc/limits.conf is reached and my machine is unbearably slow.
2: my machine freezes after a while

Which makes debugging kind of hard because it requires many reboots.

Does someone know what could be happening ?

I would appreciate any help anyone could give me !

phlipant
03-01-2004, 12:17 PM
if i understand what you are trying to do, maybe the system function would work better.

bleakcabal
03-01-2004, 01:39 PM
Yeah I think this will save me some troubles. Thanks, I did not know this system() function existed in the first place :( (shame on me)

phlipant
03-01-2004, 08:56 PM
it`s ok. i`ve been at this unix/c/c++ thing for more than 20 years. i`ve got some of it down, with plenty more to learn.

thats why i love justlinux.

sploo22
03-01-2004, 09:11 PM
This may not be the problem, but you're supposed to call wait() from the parent, not the child, like this:


pid = fork();
if (pid == -1) {
printf("\nError");
}
else if (pid == 0) {
execv(myStrCat("/bin/", cmd[0]), cmd);
}
else wait(NULL);

bleakcabal
03-01-2004, 11:16 PM
pid = fork();
if (pid == -1) {
printf("\nError");
}
else if (pid == 0) {
if (execv(myStrCat("/bin/", cmd[0]), cmd) == -1) {
exit(3);
}
}
else {
wait(NULL);
}


I have changed the code to this and now my bug seems to be gone.