Skip to content

Instantly share code, notes, and snippets.

@pzakha
Created May 25, 2017
Embed
What would you like to do?
sockpair_dgram
all:
gcc -Wall -lsocket -o sockpair_dgram sockpair_dgram.c
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
void child(int socket)
{
char hello[] = "hello parent, I am child";
struct msghdr msg = { 0 };
struct iovec io = { 0 };
io.iov_base = hello;
io.iov_len = sizeof(hello);
msg.msg_iov = &io;
msg.msg_iovlen = 1;
if (sendmsg(socket, &msg, 0) <0)
perror("sendmsg failed");
}
void parent(int socket)
{
char buf[1024] = {0};
int n;
struct msghdr msg = { 0 };
struct iovec io = { 0 };
io.iov_base = buf;
io.iov_len = sizeof(buf);
msg.msg_iov = &io;
msg.msg_iovlen = 1;
if ((n = recvmsg(socket, &msg, 0)) < 0) {
perror("recvmsg failed");
return;
}
printf("parent received '%.*s'\n", n, buf);
}
void socketfork()
{
int fd[2];
static const int parentsocket = 0;
static const int childsocket = 1;
pid_t pid;
socketpair(PF_LOCAL, SOCK_DGRAM, 0, fd);
pid = fork();
if (pid == 0) {
close(fd[parentsocket]);
child(fd[childsocket]);
} else {
close(fd[childsocket]);
parent(fd[parentsocket]);
}
exit(0);
}
int main(int argc, char *argv[])
{
socketfork();
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment