#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(int argc, char* argv[]){
    int parent_pip[2];
    int child_pip[2];
    int parent_fd = pipe(parent_pip); // create a one-way communication channel,[0]->read,[1]->written
    int child_fd = pipe(child_pip); // fd is ABBR of 'file discriptor'
    

    if(parent_fd== -1){
        printf("pipe1 error");
    }
    if(child_fd== -1){
        printf("pipe2 error");
    }

    int pid = fork(); // create a child process,whose return value is 0
    char buf[32];
    if (pid == 0) { // child
        close(child_pip[0]);
        close(parent_pip[1]);
        read(parent_pip[0], buf, 4);

        printf("%d: received ping\n", pid);

        write(child_pip[1], "pong", strlen("pong"));
        exit(0);
    }
    else{ // parent
        close(child_pip[1]);
        close(parent_pip[0]);
        write(parent_pip[1], "ping", strlen("ping"));
        wait(0); // ensure the output sequence is ordered!!!

        read(child_pip[0], buf, 4);

        printf("%d: received pong\n", pid);
        exit(0);
    }

}