Monday, 15 February 2010

c++ - Pipe is not working correctly in the parent-child process -



c++ - Pipe is not working correctly in the parent-child process -

as have started these concepts might missing out few simple things. so, please help me building knowledge domain. trying link parent , kid processes (created fork() function) using pipe. in parent process, wanted write in pipe descriptor (af[1]) , after closing write end, wanted read read end of pipe descriptor (af[0]) in kid process. here code:

#include <iostream> #include <unistd.h> #include <sys/types.h> #include <cstdlib> #include <sys/wait.h> #include <sys/types.h> #include <string.h> using namespace std; int main() { pid_t pid1; pid1 = fork(); int af[2],nbytes,wbytes; pipe(af); char inside[20]; if(pid1 == -1) { cout << "no kid process formed: " << getpid() <<endl; exit(1); } else if(pid1 == 0) { cout<< "inchild" <<endl; close(af[1]); nbytes = read(af[0],inside,strlen(inside)); cout << "read bytes: "<< nbytes << endl; cout << "child(read) within descriptor: " << within << endl; close(af[0]); cout << "in child's end" << endl; exit(0); } else { cout<< "inparent" << endl; close(af[0]); wbytes = write(af[1],"hello world",12); cout<< "wrote bytes: " << wbytes<<endl; cout << "parent(write) within string: " << af[1] << endl; close(af[1]); cout << "in parent's end" << endl; exit(0); } homecoming 0; }

then expecting run follows:

goes parent -> write string, close write end, goes kid -> read string inside, show result of string (hello world), close read end.

but getting here result:

inparent shashish-vm@shashishvm-virtualbox:~/desktop$ inchild read bytes: 0 child(read) within descriptor: a��m�n��sf� in child's end

and still not terminating. using ubuntu 14.04 lts on oracle vm virtualbox (32-bit o.s.). , have no thought why doing this. knew job of scheduler switch processes still pipe functionality of ipc not working there. write process occurred if removed close(af[0]) statement still reading not happening properly. so, please oblige me suggestions , consider me noob while sharing views. appreciate it. thanks.

you problem open pipe after calling fork. means parent , kid have different pipes. can prepare moving phone call pipe before fork create single linked pipe.

c++ linux fork pipe

No comments:

Post a Comment