Commit da69bff3 authored by Zhaozhong Liu's avatar Zhaozhong Liu
Browse files

Lab 2.1 completed

parent 517555b8
#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 fd[2];
pid_t pid;
//create the pipe
if (Pipe(fd) == -1){
fprintf(stderr,"Pipe failed");
return 1;
}
//fork a child process
pid = fork();
if (pid<0){ //error occurded
fprintf(stderr, "Fork Failed");
return 1;
}
if (pid>0){
//parent
//close the unused end of the pipe
close(fd[READ_END]);
//write to pipe
int i;
for (i = 0; i < strlen(write_msg)+1; i++){
write(fd[WRITE_END], &write_msg[i], 1);
}
//close the read end of the pipe
close(fd[WRITE_END]);
}
else{
//child
//close the unused end of the pipe
close(fd[WRITE_END]);
//read from the pipe
int read_return = 1;
int i =0;
while(read_return != 0){
read_return = read(fd[READ_END],&read_msg[i], 1);
printf("%c", read_msg[i]);
i ++;
}
printf("\n");
//close the write end of the pipe
close(fd[READ_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