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.
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.
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.
Use a signal. Choose one of the utility signals, and have the parent send it to the child after the write.
精彩评论