IPC using fork() and pipe() IPC using fork() and pipe() unix unix

IPC using fork() and pipe()


The strcmp() returns 0 on success. But there are also several other problems with your code:

  1. The string will never be equal to "Bye!", there is going to be a new line attached as well as the null character indicating the end of string (total of 6 chars).

  2. The pipes use streams not "packets" you never know how many bytes you will receive from one call to read(). It might be incomplete string or if the data is sent very fast you might get 2 strings glued to each other. You need to implement your own "protocol" to parse the data out of the stream.

  3. You are not checking if the pipe was closed on the other side (read would return 0)

  4. You get extra new line in the output because it is attached to the string read by fgets()

  5. Output may be messed up because you have no control on when processes flush to stdout (sort of a racing condition but it will not crash).


Because of the newline captured by fgets you need to test the exit condition for Bye!\n which includes that newline. strcmp(buffer, "Bye!\n")

This is in addition to fixing the negation issue pointed out by @blackpen.


Your program has several issues.

First, when fgets() reads a line, the newline at the end is included (if there was sufficient space in the buffer). The extra newlines you're seeing are because the string you send contains one, then you add another when you print it in the receiver. Also, you're looking for the string, "Bye!" to decide when to quit... but the string you actually get is "Bye!\n". You need to either strip the newline off the end of the string you read from stdin in the sender, or account for the newline already in the string when you print it and in your comparisons.

Second, in the sender, you have your logic inverted when checking when to quit: You're setting end_call = true; when buffer doesn't contain "Bye!", instead of when it does. This causes the sender to exit after sending the first string rather than looping (also, the comparison needs to be fixed to account for the newline as mentioned above). It's not the receiver that stops early, it's the sender... the receiver runs forever due to the next issue.

In the receiver, you're clearing the buffer at the end of your loop, right before you check for "Bye!" in the loop test. That prevents the comparison in the loop test from ever finding a match, so the loop is infinite. Clear the buffer at the start of the loop before fgets() instead. (And once again, fix the comparison to account for the newline at the end).