hi I'm having some problems with my c program. The goal is to fork
twice and then pass some data with pipe
from child two to child one and then some different data from child one to parent and finally print it out in parent. Here is my code:
int main(void)
{
int f,f2,nread;
int pfd[2], pfd2[2];
char buffer[512], *str;
if(pipe(pfd)==-1) {
errorHandler("pipe");
}
if((f=fork())==-1) {
errorHandler("fork 1");
} else if(f == 0) {
/*child 1*/
if(pipe(pfd2)==-1) {
errorHandler("pipe 2");
}
if((f2=fork())==-1) {
errorHandler("fork 2");
} else if(f2 == 0) {
/*child 2*/
close(pfd[0]);
close(pfd[1]);
close(pfd2[0]);
str = "rollin";
printf("-child 2 writing: %s\n", str);
if(write(pfd2[1], &str, BUFFSIZE)==-1) {
errorHandler("write 2");
}
} else {
/*child 1*/
close(pfd[0]);
close(pfd2[1]);
if((nread=read(pfd2[0], &buffer, 512))==-1) {
errorHandler("read child 1");
}
buffer[nread] = 0;
printf("child 1 read data %d [%s]\n", nread, buffer);
str = "patrollin patrolling hehe";
printf("-child 1 writing %s\n", str);
if(write(pfd[1], &str, BUFFSIZE)==-1) {
errorHandler("write");
}
}
} else {
/*parent*/
close(pfd[1]);
if((nread=read(pfd[0], buffer, sizeof(buffer)))==-1) {
errorHandler("read");
} else {
buffer[nread] = 0;
printf("parent read data: %d [%s]\n", nread, buffer);
}
}
return 0;
}
The output is that the data is read(512 bytes as I specified) but it is not what i sent. I take some random signs from the memory instead(file descriptors are passeed properly, right?). The reason I came here is I cannot figure out what is wrong with this. I have a program with only one fork and similar action and it's based on the same techniques and it is working. Can anyone give me a hint what am I doing wrong?
The second argument to read
is a pointer to the buffer. The second argument to write
is a pointer to the data to write. So you should use
read(pfd2[0], buffer, 512)
and
write(pfd2[1], str, BUFFSIZE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.