Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab5/pipe.c
221 views
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <unistd.h>
5
#include <sys/types.h>
6
7
int main(void)
8
{
9
int fd[2], nbytes;
10
pid_t childpid;
11
char string[] = "Hello, world!\n";
12
char readbuffer[80];
13
14
pipe(fd);
15
16
if((childpid = fork()) == -1) {
17
perror("fork");
18
exit(1);
19
}
20
21
if(childpid == 0) {
22
printf("Child process closes up input side of pipe\n");
23
close(fd[0]);
24
25
printf("Child: Send string through the output side of pipe\n");
26
write(fd[1], string, (strlen(string)+1));
27
printf("Child: Exiting\n");
28
exit(0);
29
}
30
else {
31
printf("Parent process closes up output side of pipe\n");
32
close(fd[1]);
33
34
printf("Parent: Read in a string from the pipe\n");
35
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
36
printf("Parent: Received string: %s", readbuffer);
37
}
38
return(0);
39
}
40
41