Here i am trying to create a simple client and a server using pipes. I fork a process to make the child act as a client and parent as the server. Below is the code:
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void errorMsg(char* msg)
{
printf("\n%s\n", msg);
// exit(0);
}
int main()
{
int servfd[2];
int clntfd[2];
int chldpid;
if(pipe(servfd) < 0)
errorMsg("Unable to create server pipe.!!");
if(pipe(clntfd) < 0)
errorMsg("Unable to create client pipe.!!!");
if((chldpid = fork()) == 0)
{
char* txt = (char*) calloc(256, sizeof(char));
close(servfd[1]);
close(clntfd[0]);
printf("@Client: Enter a string: ");
//scanf("%s", txt); //or fgets
printf("Entered.!!");
int n;
txt = "Anything that you want will not be considered no matter what you do!!";
char txt1[256];
write(clntfd[1], txt, 256);
//if(txt1[strlen(txt1) - 1] = '\n')
//{ printf("asdasdas");
//txt[strlen(txt) - 1] = '\0';}
//int i = 0;
//for(i = 0; i < 256; i++)
//printf("%c", txt1[i]);
while((n = read(servfd[0], txt1, 256)) > 0)
printf("\nAt client: %d bytes read\n\tString: %s\n", n, txt1);
}
else
{
//printf("Parent: \n\n");
close(servfd[0]);
close(clntfd[1]);
char* txt = NULL;
int n, n1;
n = read(clntfd[0], &txt, 256);
printf("Server read: %d", n);
n1 = write(servfd[1], &txt, 256);
printf("Server write: %d", n1);
wait(chldpid);
}
exit(0);
}
Question 1:
This is what is happening. When i run the program, it only prints Anything that yo (exactly 16 chars) and nothing else. When i tried to see the complete contents of txt1 using the for loop shown in comments, i found that there is null value (God knows from where) after yo in txt1. After it there are normal contents as they should be. Any idea why this is happening?
Edit:
The number of bytes read and written, when i try to print them at appropriate places, are all correct. It prints 256 bytes read. However, the size of txt1 by strlen comes out to be ’16’. Also, the program hangs after printing part of the string.
Question 2:
When i try to get a string from user using scanf or fgets also shown in comments, the program terminates as soon as i press enter. No clue about that too as of why that could be happening.
Any insight on the behaviors would be helpful. Sorry for multiple questions. Thanks for your time.! I am using ubuntu 12.04, if that could be of any help.
I have added various comments and corrections to your code. it now works as intended.
Your main issue was as pointed out by codeaddict that you did not allocate buffers. I was surprized that you didn’t crash with a SIGSEGV.