在 Linux/Unix 中用 C 语言管理进程分支

发布于 2024-10-07 23:35:58 字数 221 浏览 1 评论 0原文

我想知道如何让子进程在其父进程执行特定操作后等待执行语句。

我的需求相当简单,我只需要用 fork 生成子进程,让父进程向文件写入一些内容,然后让子进程向文件写入一些内容,然后它们都完成执行各自的命令。

我只了解了如何使用 wait() 和 waitpid() 让子进程首先执行,然后让父进程执行,但这显然在这里不起作用。

有什么想法吗?

非常感谢您的帮助,谢谢。

I am wondering how you can get a child process to wait to execute a statement after it's parent does a particular thing.

My needs are fairly simple, I just need to spawn the child process with fork, have the parent write something to a file, then have the child write something to the file, then they both finish executing their separate commands.

I've only learned about using wait() and waitpid() to have child processes execute first, then have the parent execute, but that obviously won't work here.

Any ideas?

Help is greatly appreciated, thanks.

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

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

发布评论

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

评论(3

在你怀里撒娇 2024-10-14 23:35:58

您可以在父级和子级之间使用pipe()。父级完成写入文件后,父级通过管道向子级写入数据。

You can use a pipe() between the parent and child. The parent writes to the child via the pipe after the parent has finished writing to the file.

叶落知秋 2024-10-14 23:35:58

为什么不让父进程在生成子进程之前编写它呢?

如果这不起作用,你真的应该考虑 fork 是否是适合这项工作的工具,我在这里看到了很多与 fork 相关的问题,可能是这是一些 70 年代埋头苦干的老教授没有意识到 POSIX 线程是大多数此类工作的工具的结果。实际上,fork 的唯一合法用途是运行外部程序(但 posix_spawn 是一个更好的接口)并移交重量级客户端连接(如 ssh 会话)到一个全新的进程,出于安全目的,该进程需要调整其权限并将其自身与其他会话隔离。

Why don't you have the parent do its writing before spawning the child?

If that won't work, you really should think about whether fork is the right tool for the job I've seen a lot of fork-related questions here, probably as a result of some old-timer professor with his head buried in the 70s not being aware that POSIX threads are the tool for most such jobs. Really the only legitimate uses for fork are running external programs (but posix_spawn is a better interface for doing so) and handing off heavy-weight client connections (like ssh sessions) to a completely new process that needs to adjust its privileges and isolate itself from other sessions for security purposes.

小伙你站住 2024-10-14 23:35:58

使用信号。选择实用程序信号之一,并让父级在写入后将其发送给子级。

Use a signal. Choose one of the utility signals, and have the parent send it to the child after the write.

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