How to fork() and exec() in this one?
I'm writing my own shell, but no fork gives my child_pid = 0... What's wrong there?
while(true)
{
read_command(command);
if ((child_pid = fork()) == -1)
{
fprintf(stderr, "can't fork\n");
exit(1);
}
else if (child_pid == 0) //child
{
status=execl("./myShell" command);
}
else
{
wait(status); //parent
开发者_如何学C}
}
I guess that the (child_pid == -1)
is not entered... Is the father (else
) branch entered twice (by both process) or what?
Anyway I can't see a bug in that snippet of code. If you're sure your execution flow gets there, and has an unpredictable behavior its because of a bug.
I doubt glibc is bugged on your system: my best guess is that your program has got a broken pointer that broke everything. This is the most common cause of this kind of really weird behaviors.
Your code is OK. Add a debug print in if(child_pid == 0)
and make sure it is not called. If fork
cannot create a child, it sets errno
to indicate the error occurred.
精彩评论