c - "Bad file descriptor" error, when using file descriptors of the socketpair function more than once -
The following code sends messages to their parents by sending their parents to the socket pair.
Add # & lt; Sys / types.h & gt; # Include & lt; Sys / socket.h & gt; # Include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; #include & lt; String.h & gt; #defined message "hello" ent main () {four messages [100]; Int i, pdfurk, socket [2]; / * * Trying to use a socketpayer function * * (if socketpayer (aufunix, SOCAKRRM, 0, sockets) == -1) {* peer ("make socketpair"); * Exit (-1); *} For (i = 0; i & lt; 2; i ++) {if (socketpayer (f_UNEX, SOCAKRRM, 0, sockets) == -1 (retaliation ("making socketpayer"); exit (-1);} Printf ("i:% d \ n", i); PidFork = fork (); If (pidFork == -1) {perror ("make baby process"); exit ( -1);} And if (pidFork! = 0) {// Basic Closed (Chairs [0]); if (Read (Sockets [1], Message, Stellen (Message)) == -1) {Mess ("Data reading"); exit (-1);} Printf ("data:% s \ n \ n", message); close (socket [1]);} Else {// hair pass (socket [ 1]); if (l (Socket [0], Message, Stellen (Message)) == -1) {Explanation ("Writing Data"); Exit (-1);} Pass (Chairs [0]); Exit (0);}} Return 0;} First of all, I tried to get the file descriptor for a socket pair with socket pair, before entering it for loop , Like showcased lines, but it works only the first to run on the second, let me have a "bad file Descriptor error "would have loved the way I worked it was going to be inside the loop calls Soketpeyr function I, however, when the first approach using the pipe work for me.
So I would like to know why this happens, Am I making a mistake? What is the difference between the IPC system?
Update: There is no difference between file descriptors of pipes and sockets, I think it is working with pipes. Because there is an error in the second part of my entire program. The accepted answer resolved my problem.
You are closing both ends of socketpair parents and In both the children In general, use a socket pair or pipe per hair process.
Comments
Post a Comment