Reputation: 179
I am trying to to create a socket that communicates with two child processes that have been forked, a and b. I need it to communicate via the socket sc. As a starting point, I am trying to get Process a to write a message to Process b via the sc socket, but so far everything I've tried results in the printing of an error message.
Below is my code. Any ideas on how to finally make it work? (My ultimate goal is to do reading and writing of more than one message, so any advice on that is a definite bonus.) Thanks in advance for any help provided.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main() {
pid_t a, b;
int sc;
struct sockaddr server = {AF_UNIX, "server"};
sc = socket(AF_UNIX, SOCK_STREAM, 0);
bind(sc, &server, sizeof(server));
listen(sc, 1);
if ((a = fork()) == 0) {
struct sockaddr me = {AF_UNIX, "ProcessA"};
struct sockaddr there = server;
int s = socket(AF_UNIX, SOCK_STREAM, 0);
char buffer[256];
sprintf(buffer, "test");
if (bind(s, &me, sizeof(me)) < 0) {printf("Error binding\n"); exit(1);}
if (connect(s, &there, sizeof(there)) < 0) printf("Error connecting\n");
write(s, buffer, strlen(buffer) + 1);
printf("Process A\n");
exit(0);
}
else if ((b = fork()) == 0) {
struct sockaddr address;
int length;
length = sizeof(address);
int c, n;
char buffer[256];
if ((c = accept(sc, &address, &length)) < 0) {printf("Error accepting\n"); exit(1);}
if ((n = read(c, buffer, 255)) < 0) {printf("Error reading\n"); exit(1);}
printf("Log Process\n");
printf("%s\n", buffer);
exit(0);
}
return 0;
}
I keep getting the messages "error binding" and "error accepting" - Once more, thank you.
Upvotes: 1
Views: 1509
Reputation: 6214
From Beej's Guide:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void)
{
int sv[2]; /* the pair of socket descriptors */
char buf; /* for data exchange between processes */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
perror("socketpair");
exit(1);
}
if (!fork()) { /* child */
read(sv[1], &buf, 1);
printf("child: read '%c'\n", buf);
buf = toupper(buf); /* make it uppercase */
write(sv[1], &buf, 1);
printf("child: sent '%c'\n", buf);
} else { /* parent */
write(sv[0], "b", 1);
printf("parent: sent 'b'\n");
read(sv[0], &buf, 1);
printf("parent: read '%c'\n", buf);
wait(NULL); /* wait for child to die */
}
return 0;
}
Note: consider closing the socket you're not using after the fork: close(sv[0]);
in the child case; close(sv[1]);
in the parent case.
Upvotes: 5