1.socketpair
2.sendmsg/recvmsg
3.UNIX domain socket pass-through description word
Function: Create a loop duplex flow pipeline
Prototype:
int socketpair (int domain, int type, int protocol, int sv[2]);
Parameter domain: protocol family
Type: Socket type
Protocol: Protocol Type
SV: The returned socket pair
Return value: Successfully returned 0, failed to return-1
Full-duplex pipeline created through Sockpair to enable parent-child process communication
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#defineErr_exit (M) Do{perror (M); Exit (Exit_failure); } while(0)intMainintargcConst Char*argv[]) { intsockfds[2]; intRET = socket (Pf_unix, Sock_stream,0, Sockfds); if(ret = =-1) Err_exit ("Sockpair"); pid_t pid; PID=Fork (); if(PID = =-1) Err_exit ("Fork"); if(PID >0) { intval =0; Close (sockfd[1]); while(1) { ++Val; printf ("sending data:%d\n", Val); Write (sockfds[0], &val,sizeof(Val)); Read (sockfd[0], &val,sizeof(Val)); printf ("data received:%d\n", Val); Sleep (1); } }Else if(PID = =0) { intVal; Close (sockfds[0]); while(1) {Read (sockfds[1], &val,sizeof(Val)); ++Val; Write (sockfds[1], &val,sizeof(Val)); } } return 0; }
It is found that the value of Val is constantly increasing and is being passed on between parent and child processes;
Let's take a look at the more powerful sendmsg function
ssize_t sendmsg (int sockfd, const Span style= "COLOR: #0000ff" >struct msghdr *msg, int flags);
struct MSGHDR {
void *msg_name; /* Optional Address */
Socklen_t Msg_namelen; /* Size of Address */
struct Iovec *msg_iov; /* Scatter/gather Array */
size_t Msg_iovlen; /* # elements in Msg_iov */
void *msg_control; /* Ancillary data, see below */
size_t Msg_controllen; /* Ancillary Data buffer Len */
int msg_flags; /* Flags on received message */
};
Parameter explanation:
1.void *msg_name; /* Optional Address */
Socklen_t Msg_namelen;
These two parameters determine the address to send
2. struct Iovec *msg_iov; /* Scatter/gather Array */
The data we want to send is stored in this structure.
struct Iovec {
void *iov_base; /* Starting address */This corresponds to buffer
size_t Iov_len; /* Number of bytes to transfer */buffer length
};
Structure above
++++++
This is a MSGHDR.
3. Secondary information when the next few data.
We implement pass descriptors through our own encapsulation sendmsg
Write a Send Yourself
Linux: Using Socketpair to pass descriptors between processes