如何在其中 fork() 和 exec() ?

发布于 2024-10-02 05:28:18 字数 446 浏览 0 评论 0原文

我正在编写自己的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七堇年 2024-10-09 05:28:18

我猜想 (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.

榕城若虚 2024-10-09 05:28:18

你的代码没问题。在 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. If fork cannot create a child, it sets errno to indicate the error occurred.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文