如何在其中 fork() 和 exec() ?
我正在编写自己的 shell,但没有 fork 给我的 child_pid = 0... 那里出了什么问题?
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜想
(child_pid == -1)
没有输入...是父亲 (else
) 分支输入了两次(由两个进程)还是什么?无论如何,我在该代码片段中看不到错误。如果您确定您的执行流程到达那里,并且由于错误而出现不可预测的行为。
我怀疑 glibc 在你的系统上被窃听了:我最好的猜测是你的程序有一个损坏的指针,破坏了一切。这是这种非常奇怪的行为的最常见原因。
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.
你的代码没问题。在
if(child_pid == 0)
中添加调试打印并确保它未被调用。如果fork
无法创建子进程,它会设置errno
来指示发生了错误。Your code is OK. Add a debug print in
if(child_pid == 0)
and make sure it is not called. Iffork
cannot create a child, it setserrno
to indicate the error occurred.