Commit 517555b8 authored by Zhaozhong Liu's avatar Zhaozhong Liu
Browse files

update

parent efba7274
CC = gcc
CFLAGS = -std=gnu99 -Wall -g #-DDEBUG
LFLAGS = -lpthread -lm
EXECS = pthread_hello time_demo mergesort
all: EXECS
heap-test: heap-test.c
$(CC) $(CFLAGS) -o $@ $<
pipe-test: pipe-test.c
$(CC) $(CFLAGS) -o $@ $<
.PHONY: clean
clean:
/bin/rm -f *.o $(EXECS)
CC = gcc
CFLAGS = -std=gnu99 -Wall -g #-DDEBUG
LFLAGS = -lpthread -lm
EXECS = pthread_hello time_demo mergesort
all: EXECS
pthread_hello: pthread_hello.c
$(CC) $(CFLAGS) -o $@ $< $(LFLAGS)
fork: fork.c
$(CC) $(CFLAGS) -o $@ $<
time_demo: time_demo.c
$(CC) $(CFLAGS) -o $@ $<
mergesort: parallelMergesort.c
$(CC) $(CFLAGS) -o $@ $< $(LFLAGS)
func_dice_test: func_dice_test.c functional_dice.h
$(CC) $(CFLAGS) -o $@ func_dice_test.c
impe_dice_test: impe_dice_test.c imperative_dice.h
$(CC) $(CFLAGS) -o $@ impe_dice_test.c
.PHONY: clean
clean:
/bin/rm -f *.o $(EXECS)
1) The parent and children do not share the heap, and that's why the child can not read
what the parent wrote.
2)It is because the child inherits open files from parent, and pipe is also
an open file.
3)To create a pipe requires a fd array which is used to return two file descriptors referring
to the ends of the pipe.To create a file, you need to have a path as input. Also, files have one fd while pipe as an array of 2 fds . pipefd[1] refers
to the write end and pipefd[0] is the read end. For file, you also have read and write,
but you do them with read() and write() functions
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
//allocate some space on the heap, data type:int
int *pointer;
pointer = malloc(sizeof(int));
*pointer = 0;
int pid;
pid = fork();
if (0 == pid){
int *num1 = *pointer;
printf("child reads: %d\n", num1);
exit(0);
}
else{
*pointer = 100;
int *num2 = *pointer;
printf("parent reads: %d\n", num2);
exit(0);
}
}
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.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){
//close the unused end of the pipe
close(fd[READ_END]);
//write to pipe
write(fd[READ_END], write_msg, strlen(write_msg)+1) ;
//close the read end of the pipe
close(fd[WRITE_END]);
}
else{
//close the unused end of the pipe
close(fd[WRITE_END]);
//read from the pipe
read(fd[READ_END],read_msg, BUFFER_SIZE);
printf("read %s", read_msg);
//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