#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
        int fd[2]; /* Array of size two, fd[0] is the read-end, f[1] is the write-end.*/
        pid_t var_pid;
        int returned;

        returned = pipe(fd);  /* Returns 0 on success, -1 on error.*/
        var_pid = fork();

        if (var_pid < 0  || returned < 0)
        {
            printf("Problem!");
            exit(1);
        }

        if(var_pid == 0) /* Child process */
        {
            close(fd[0]); /* Close read-end, so that the parent can detect an end-of-file.*/
            write(fd[1], "Hello, world!\n", 14);
            exit(0);
        }
        else /* Parent process */
        {
            char readbuffer[100];
            close(fd[1]); /* Close write-end.*/
            read(fd[0], readbuffer, sizeof(readbuffer)); /* Blocking read*/
            printf("I received the following: %s", readbuffer);
            exit(0);
        }
}

/*
 *
 * Modifications suggestions
 * ==========================
 *
 * Try to enhance (or break!) this program by doing the following. You can do them all at once, one after the other, and work on them in any order, but just make sure you create copies of your programs.
 *
 * a) String manipulation
 * -----------------------
 *
 * - Use a variable for the string passed as a parameter of write.
 * - Use the strlen function from <string.h> to compute the length of the string passed as a parameter of write, i.e., you should use something like
 * write(fd[1], string_var, (strlen(string_var)+1));
 * - Why do we add one to the length of the string ?
 *
 * b) "Reverse the pipe"
 * ----------------------
 *
 * - Modify your program so that the parent writes into the pipe, and the child reads.
 * - Make the parent waits for the child to complete. You'll need to include <sys/wait.h> to access the wait function. Undo that modification afterward.
 * - Make the parent, or the child, sleep for three seconds, using sleep(3).
 *
 * c) Messing with the string
 * ----------------------------
 *
 * - Modify the readbuffer and/or the read instruction so that the length of the string to read exceeds the capacity of the buffer.
 * - Read two times from the pipe.
 * - Write two times in the pipe.
 *
 * d) Messing everything up
 * ------------------------
 *
 * - Don't close any side of the pipe.
 * - Write in the pipe with the process that used to read only.
 * - Read in the pipe with the process that used to write only.
 * - Make the process that write then read wait a bit, using sleep(3).
 * - Well, that worked surprisingly well. Can you think of scenario were that would go wrong, though? Try to break the program using the pipe in two ways.
 *
 *
 */

