我想用管道和信号制作一个 REPL 风格的程序,但是我的程序锁定了

发布于 2024-12-11 10:50:22 字数 567 浏览 0 评论 0原文

程序应该分叉,然后父进程应该读取用户输入,并将其发送给子进程;孩子应该处理它,然后将结果发送给父母,父母打印它(需要以这种方式工作)。

我已经完成了其中的一部分,但是程序在第一次从 fifo 读取后锁定。

我怀疑问题出在第 122-199 行之间。使管道非阻塞会使程序在 185 处跳转到 scanf 并无限循环。在写入之前和读取之后关闭并重新打开管道会产生相同的效果。

以下是来源:链接


稍后编辑(澄清):

当读取第二个命令时,父级在 184 处的 printf 之前阻塞(第一次似乎工作得很好)。

我还没有实现“孩子将东西发送回父母”部分。目前我只想让子进程输出通过管道从父进程接收到的数据,然后将控制权交还给父进程以读取另一个命令。

子进程处于暂停状态 (pause()),而父进程读取输入并通过管道发送输入,然后唤醒子进程并使其本身进入暂停状态。子进程从管道中读取数据并输出,然后唤醒父进程并进入睡眠状态。

The program should fork, then the parent should read user input, send it to the child; the child should deal with it, then send a result to the parent, who prints it (it is required to work this way).

I've done a part of it, but the program locks after reading from the fifo the first time.

I suspect the problem is somewhere between lines 122–199. Making the pipe nonblocking makes the program jump through the scanf at 185 and loop indefinitely. Closing and reopening the pipe before writing and after reading leads to the same effect.

Here is the source: link.


Later edit (clarification):

The parent blocks before the printf at 184, when it reads the second command (the first time it seems to work just fine).

I haven't implemented the "child sends stuff back to the parent" part. At the moment I just want to make the child output the data it recieves through the pipe from the parent and then give control back to the parent to read another command.

The child lives in a paused state (pause()) while the parent reads input and sends it through the pipe, then it wakes up the child and goes in a paused state itself. The child reads data from the pipe and outputs it, then wakes up the parent and goes to sleep.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

不寐倦长更 2024-12-18 10:50:22

您是否使用了一些多路复用系统调用,例如 selectpoll ,它们能够测试一组文件描述符是否已准备好其中一些(用于输入或输出)?

了解有关民意调查选择 和朋友。

Did you use some multiplexing system call like select or poll which are able to test of a set of file descriptors has some of them ready (for input, or for output)?

Learn more about poll or about select and friends.

你如我软肋 2024-12-18 10:50:22

您应该澄清您的问题,其中部分(父母或孩子)是锁定的。

确保所有输出均以换行终止。看起来(从快速阅读来看)您使用了 puts() ,它应该可以解决这个问题。

尝试在客户端完成后对输出调用 fflush() ,以确保如果子级在父级读取其输出时继续存在,则输出被写入管道。我没有仔细阅读您的代码来追踪生命周期处理。

You should clarify your question which with part (parent or child) it is that locks.

Make sure all output is line feed terminated. It seems (from a quick reading) that you use puts(), which should take care of that.

Try calling fflush() on the output after the client is done, to make sure the output gets written to the pipe, if the child lives on while the parent reads its output. I didn't read your code closely enough to track down the lifetime handling.

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