Search code examples
clinuxforkhaproxyunix-socket

unix socket creation then fork(), messaging gets mixed up


I'm currently trying to solve an issue where I create a process A, which creates a Unix socket to connect to a server process. I then fork the process A and get a new child process B. At this point I have 2 processes, with duplicate descriptors,etc.. when process B sends a message to the server, the server processes the message and then sends it back to process A (but it should go back to process B). I am certain this is because A and B are duplicates, and somehow the Unix socket from the server's perspective is still a " process A socket", and all messages will go back to A no matter who sends them.

Is there any way to resolve this other than disconnecting and reconnecting post-fork in both processes A and B? (The process A and B are haproxy in master/worker mode)? Thanks!


Solution

  • I did some additional research and there is another way to do this, I learned about pthread_atfork() which sets up functions to be called by the parent and the child upon fork.. i actually used this mechanism to stop and start the network functionality on the child, and it worked!

    https://linux.die.net/man/3/pthread_atfork