0
votes

I have written a basic c++ program in unix with fork() and wait() system call. I am only creating one child. I have used two pipes. So After fork operation with first pipe i am writing from child to parent and as after parent receives the data, parent is writing back to child in second pipe. after that in parent side I am using wait(0) system call. but still my parent process dies before child process?

structure is something like this:

 main()
 char buff[] = "Parent process kills";
 char cuff[] = "before Child process";
 int fd1[2];
 int fd2[2];
 pipe(fd1);
 pipe(fd2);
 if((pid = fork()) == 0)
 {
   close(fd1[0]);
   close(fd2[1]);
   write(fd1[1],buff,strlen(buff)+1);
   read(fd2[0],cuff,sizeof(cuff));

 }
 else
 {
    close(fd1[1]);
    close(fd2[0]);

    read(fd1[0],buff,sizeof(buff));
    write(fd2[1],cuff,strlen(cuff)+1);
    wait((int *) 0);
  }

  close(fd1);
  close(fd2);

  }'

Even though wait() is used but still parent process dies before child. Thanks in adavance.

3
Remember that fork can fail, and in that case returns -1. So your if statement will not work in that case. You should always check return values for failures. - Some programmer dude

3 Answers

0
votes

Your call to read result in undefined behavior. You try to read into string literals, not the buffers you have. In this case it probably results in a crash.

Your write calls also writes a string literal and not the buffer you have.

Also, since you have character arrays initialized to strings, sizeo(buff) and strlen(buff) + 1 are equal.

0
votes

Are you sure you're not dying due to a segfault? Each of these commands is trying to send more than you intend:

write(fd1[1],"buff",strlen(buff)+1);

and

write(fd2[1],"cuff",strlen(cuff)+1);

and each of these is trying to receive into read-only memory:

read(fd2[0],"cuff",sizeof(cuff));

and

read(fd1[0],"buff",sizeof(buff));
0
votes

There is a subtle error in the line

if(pid == fork())

You compare the result of fork() with pid instead of assigning to it and comparing it to zero. What you wanted to write is this:

if((pid = fork()))

Note the extra set of parentheses that tells the compiler that you really want to do the assignment, and that you don't want get a warning on it.

And with the corrected if, you have the parent executing the first case, not the second, so the correct code would be:

if(pid == fork()) {
  close(fd1[1]);
  close(fd2[0]);

  read(fd1[0],"buff",sizeof(buff));
  write(fd2[1],"cuff",strlen(cuff)+1);
  wait((int *) 0);
} else {
  close(fd1[0]);
  close(fd2[1]);
  write(fd1[1],"buff",strlen(buff)+1);
  read(fd2[0],"cuff",sizeof(cuff));
}