I know I'm going to need to use fork(), but this just creates a single child process. Do i simply call fork again from within the child process? Also, I need them to communicate through a signal or pipe, which is easier to implement and what do i need to know for doing that (functions, etc..)
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Just a little contribution, if you want to create 2 childs from the same parent you could use this code below. In which one father create 2 child processes (lazy and active).
If you run this code, you should get a similar output:
output :
In this example
they are just sleeping for a few random sec. It also has all the pid, so we can send SIGNAL to communicate...Most of the #includes are commented cause they were useless where I compiled.
To create a second process, call
fork()
again - either within the parent or the child (but not both!). Which you choose depends on whether you want this process to be a child of the original parent or a child of the first child process (it is usual for it to be a child of the original parent).Communicating through a pipe is much simpler and more reliable than using signals.
pipe()
,close()
,read()
,write()
andselect()
are the key functions here.For example, to have the parent create two child processes, you would do something like:
You can put the fork in a loop and generate as many child processes as you need. I did that on a project recently.
Log_Print() and Err_Print() are internal functions but quite obvious so I let them like they are.
There is one aspect with the variables that has to be explained.
nSon
andnSonAsked
should be declared as globals not as stack variables. This way, their value persists in the forked process. This means that thenSon
variable will have a different value in each of the children. This allows it to have a simpler numbering scheme than theownpid()
number.To get it completely right, there are a lot of details to get right. You will have to set signal handlers in the father process to detect the death of a child, likewise the other way round (only possible on Linux, other Unix (at least Solaris) do not support parent death signals). You have to be aware that open file descriptors in the father process will be also open in the child after fork and it will be the same one. This opens a lot of concurrency problems if you're not aware of it (the solution is using
dup()
andclose()
in the right places).