-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCp2_namedpipe.txt
82 lines (75 loc) · 2.38 KB
/
Cp2_namedpipe.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
void child(char *path)
{
int fd;
ssize_t num;
char buf[20];
int upper,lower;
upper = 49;
lower = -49;
for(int i =0; i< 20; i++){
buf[i]= ((rand() % upper + 1 -lower) + lower);
printf("%d", buf[i] + " \t");
}
fd = open(path, O_WRONLY);//O_WRONLY effectively makes the pipe unidirectional
if(fd==-1) {fprintf(stderr," in child, open error=%d, msg=%s\n",errno,strerror(errno)); exit(-1);}
//printf("in child, fd=%d, sizeof(buf)=%d, buf=%s\n",fd, sizeof(buf),buf);
//sleep(2);//the parent will read the message no matter whether the child sleeps or not
num=write(fd, buf, sizeof(buf));
//printf("in child, write returned num=%lu, Child sent: %s\n",num, buf);
printf(" child sent into the unamed pipe ");
for(int j = 0; buf[j] != NULL; j++){
printf( buf[j], " \t");
}
close(fd);
}//child
void parent(char *path)
{
int fd;
ssize_t num;
char buf[512];
//sleep(1);
fd = open(path, O_RDONLY);//O_RDONLY effectively makes the pipe unidirectional
if(fd==-1) {fprintf(stderr,"in parent, open error=%d,msg=%s\n",errno,strerror(errno)); exit(-1);}
//printf("in parent, sizeof(buf)=%d, fd=%d\n",sizeof(buf),fd);
num=read(fd, buf, sizeof(buf));
// printf("in parent, read returned num=%lu, Parent received: %s\n", num,buf);
printf(" parent read from the unamed pipe ");
for(int k=0; buf[k]!= NULL; k++){
printf(buf[k], "\t");
}
close(fd);
unlink(path);
}//parent
int main()
{
//char *path = "/tmp/fifo";
char path[1024];//used to store the absolute path of the file backing our named pipe
if (getcwd(path, sizeof(path)) == NULL)
{
perror("getcwd() error");
exit(0);
}
strcat(path,"/fifoTest");//now path may contain a string that looks like /home/student/Desktop/fifoTest
pid_t pid;
//set buffering method for file stream "stdout": characters are saved up until a newline is output
setlinebuf(stdout);
unlink(path);
int r=mkfifo(path, 0600);
if(r==-1) {fprintf(stderr,"in main, mkfifo call error=%d, msg=%s\n",errno,strerror(errno)); exit(-1);}
pid = fork();
if(pid<0) {fprintf(stderr,"in main, fork call error=%d, msg=%s\n",errno,strerror(errno)); exit(-1);}
else if (pid == 0) {
child(path);//child process is the writing end
} else {
parent(path);//parent process is the reading end
}
//unlink(path);
return 0;
}//main