Commit 1bb81518 authored by Zhaozhong Liu's avatar Zhaozhong Liu
Browse files

Lab 2.2 completed

parent da69bff3
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "wrappers.h"
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
int main(void){
char write_msg[BUFFER_SIZE]="Greetings";
char read_msg[BUFFER_SIZE];
int pToc[2];//the file descriptor for parent to child
int cTop[2];//the file descriptor for child to parent
pid_t pid;
//create the pipe
Pipe(pToc);
Pipe(cTop);
//fork a child process
pid = fork();
if (pid<0){ //error occurded
fprintf(stderr, "Fork Failed");
return 1;
}
if (pid>0){
printf("Parent begins\n");
//parent
//close the unused end of the pipe
close(pToc[READ_END]); //two closes bc of two pipes
close(cTop[WRITE_END]);
//write to pipe
int i;
for (i = 0; i < strlen(write_msg)+1; i++){
write(pToc[WRITE_END], &write_msg[i], 1);
}
//close the read end of the pipe
close(pToc[WRITE_END]);
wait(NULL);
//READ the message from the child
int read_return1 = 1;
i = 0; //re-initialize i to be 0
while(read_return1 != 0){
read_return1 = read(cTop[READ_END],&read_msg[i], 1);
printf("%c", read_msg[i]);
i ++;
}
printf("\n");
close(cTop[READ_END]);
}
else{
printf("Child begins\n");
//child
//close the unused end of the pipe
close(pToc[WRITE_END]);
close(cTop[READ_END]);
char character;
//read from the pipe
int read_return = 1;
int j =0;
while(read_return != 0){
read_return = read(pToc[READ_END],&read_msg[j], 1);
printf("%c", read_msg[j]);
character = toupper(read_msg[j]);
write(cTop[WRITE_END],&character,1);
j ++;
}
printf("\n");
//close the read end of the pipe
close(pToc[READ_END]);
close(cTop[WRITE_END]);
}
return 0;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment