123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- int main()
- {
- int pid, pip[2];
- char instring[20];
- char * outstring = "Hello World!";
- if (pipe(pip) < 0) {
- perror("pipe");
- return 1;
- }
- pid = fork();
- if (pid == 0)
- {
-
- close(pip[0]);
-
- int bytes = write(pip[1], outstring, strlen(outstring));
-
- close(pip[1]);
-
- if (bytes < 0) {
- perror("pipe write");
- return 1;
- } else if (bytes != strlen(outstring)) {
- fprintf(stderr, "pipe write: %d != %ld\n", bytes, strlen(outstring));
- return 1;
- }
- return 0;
- }
- else
- {
-
- close(pip[1]);
-
- memset(instring, 0, sizeof(instring));
-
- int bytes = read(pip[0], instring, sizeof(instring) - 1);
-
- close(pip[0]);
-
- if (bytes < 0) {
- perror("pipe read");
- return 1;
- } else if (bytes != strlen(outstring)) {
- fprintf(stderr, "pipe read: %d != %ld\n", bytes, strlen(outstring));
- return 1;
- } else if (memcmp(instring, outstring, sizeof(outstring)) != 0) {
- fprintf(stderr, "pipe read does not match pipe write\n");
- return 1;
- } else {
- printf("%s\n", instring);
- }
- return 0;
- }
- return 0;
- }
|