I've been doing some C on linux for an OS course.
We had an exercise on sockets. I got the basic question done, where a fork child holds one end of a socket, receives a message from the parent, prints them to screen, then sends a message back to the parent, which prints the message to screen, on an infinite loop.
There was an extra question though, where the child sends different messages to the parent, depending on the message it receives from it. That was all it said. My attempted solution is below.
It is crude in many ways, I am sure. The main problem though is that when the parent prints the messages it receives from the child, it runs over from one message into the next.
i.e. the two messages it receives in turn are "so is this" and "neither is this"
but it eventually starts printing out something like "so is this neith"
So my central, basic question is how do I get the parent to read only the sufficient amount from the socket, once strings are concatenated into it (which seems to be the case). Or rather, is there some way when writing to the socket to punctuate the messages sent to it so that the reader knows when to stop reading?
I think one of the problems is synchronization - ideally, there should only be one message to read in the socket at a time, but this is not how it has panned out.
Should I use flags to make sure that only one string is written into each end of the socket at one time?
Thanks for your help.
Here's the code: (there are probably a few unneccessary quirks in it due to various vain attemps to solve the problem)
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
main(){
int pid;
int socket[2];
int n = 1;
int m;
int p;
char buffer1[20];
char buffer2[16];
socketpair(AF_UNIX, SOCK_STREAM, 0, socket);
pid = fork();
while(n==1){
if (pid > 0){
close(socket[1]);
printf("Parent Process writing \n");
write(socket[0], "This is not a pipe\n", 20);
sleep(5);
printf("Parent Process writing \n");
write(socket[0], "This is a socket\n", 18);
sleep(5);
p = read(socket[0], buffer2, 16);
printf("Parent process reading\n");
write(1, buffer2, p);
sleep(5);
}
if (pid == 0){
close(socket[0]);
m = read(socket[1], buffer1, 20);
printf("Child Process reading\n");
write(1, buffer1, 20);
sleep(5);
if (m > 19){
printf("Child process writing\n");
write(socket[1], "Neither is this\n",16);
}
else{
printf("Child process writing\n");
write(socket[1], "So is this\n",11);
}
sleep(5);
}
}
}
Edited by ZekeDragon, 25 March 2010 - 03:20 AM.
Please use [code] tags (the # button) when posting code.


Sign In
Create Account

Back to top









