在一般的socket实现的时候,通常是用参数的形式,将文件描述符(FD)传到子进程或者直接传到read()汉书中。
不过如果想以Socket的形式,来传送FD的话,那就要用到sendmsg和recvmsg函数了。关键点,FD的值要通过msg.msg_control来传递的,千万别写到传输用的buff里面,那样做只是简单的传值,没有任何意义的。
/*
-------------------------------------------------
server
-------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <ctype.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#define PORT1 (u_short)11005
#define PORT2 (u_short)11002
/*
-------------------------------------------------
グローバル変数
-------------------------------------------------
*/
struct hostent *myhost;
char hostname[257];
char buff[257];
struct sockaddr_in me;
struct sockaddr_in aite;
int sockfd;
int fd = 0;
int s_retry_counter;
int ret;
int status;
int pid;
int aiteaddrlen;
fd_set l_fds;
int sendmsg_fd;
int recvmsg_fd;
int rcv_proc();
/*-------------------------------------------------
メインルーチン
-------------------------------------------------
*/
int main () {
int l_rtn;
struct cmsghdr *l_cmsg;
struct msghdr msg;
struct iovec iov[1];
int send_buf = 1;
int l_length;
char cms_data[sizeof(struct cmsghdr) + sizeof(int)];
int l_fd_pair[2];
if(socketpair(PF_UNIX, SOCK_STREAM, 0, l_fd_pair) != 0)
{
fprintf(stderr,"Create socketpair failed./n");
}
pid = fork();
switch(pid)
{