process - Sending characters using pipes in C -
i trying send string parent process child process using pipes in c programming language, works correctly, receive incomplete string without first character. wrong in code? thank you.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> int main(int argc, char** args) { int pid, p[2]; int status = -100; char input[100]; char inputbuffer[100]; if(pipe(p) == -1) { return -1; } if((pid = fork())<0) { printf("error\n"); } else { if(pid==0) { close(p[1]); while(1) { if(!read(p[0],&inputbuffer,1)) { close(p[0]); break; } else { read(p[0],&inputbuffer,100); } } printf("received: %s\n",inputbuffer); exit(0); } else { printf("enter string\n"); scanf("%s", &input); printf("string entered: %s\n",input); close(p[0]); write(p[1], input, strlen(input)+1); close(p[1]); wait(&status); } } return 0; }
the problem first read 1 byte see if isn't nul terminator information gone because overwrite in latter call! need increment pointer on latter call.
if(!read(p[0],&inputbuffer,1)) { close(p[0]); break; } else { char *pointer = &inputbuffer; read(p[0],pointer+1,99); }
Comments
Post a Comment