Skip to content

Instantly share code, notes, and snippets.

@Themaister
Created November 19, 2015 22:10
Show Gist options
  • Save Themaister/b1342a66b986656ec988 to your computer and use it in GitHub Desktop.
Save Themaister/b1342a66b986656ec988 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <sys/un.h>
#include <stdbool.h>
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
struct cmsgbuf
{
struct cmsghdr hdr;
int fd;
};
static bool push_handle(int socket, int fd)
{
char empty = '!';
struct iovec nothing = {
.iov_base = &empty,
.iov_len = 1,
};
struct cmsgbuf msgbuf;
struct msghdr msg = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_iov = &nothing,
.msg_iovlen = 1,
.msg_flags = 0,
.msg_control = &msgbuf,
.msg_controllen = CMSG_LEN(sizeof(int)),
};
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = msg.msg_controllen;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
int *dfd = (int*)CMSG_DATA(cmsg);
*dfd = fd;
fprintf(stderr, "Sending FD %d\n", fd);
int ret = sendmsg(socket, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
return ret > 0;
}
int main(int argc, char *argv[])
{
if (argc != 2)
return 1;
fprintf(stderr, "Running test ...\n");
int ret = 0;
int fd = open(argv[1], O_RDWR);
if (fd < 0)
return 1;
push_handle(0, fd);
close(fd);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment