Created
February 1, 2023 19:59
-
-
Save dulimarta/79ff6892a7474381a4eb6b894e265e57 to your computer and use it in GitHub Desktop.
CS452 Lab04 - Pipes - Sample 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#define READ 0 | |
#define WRITE 1 | |
#define MAX 1024 | |
int main () { | |
int fd[2]; | |
ssize_t num; | |
pid_t pid; | |
char str[MAX]; | |
if (pipe (fd) < 0) { | |
perror ("plumbing problem"); | |
exit (1); | |
} | |
// point A | |
if ((pid = fork ()) < 0) { | |
perror ("fork failed"); | |
exit (1); | |
} | |
// point B | |
else if (!pid) { | |
dup2 (fd[WRITE], fileno(stdout)); | |
// point C | |
close (fd[READ]); | |
close (fd[WRITE]); | |
//point D | |
fgets (str, MAX, stdin); | |
write (fileno(stdout), (const void *) str, (size_t) strlen (str) + 1); | |
exit (0); | |
} | |
dup2 (fd[READ], fileno(stdin)); | |
//point C | |
close (fd[READ]); | |
close (fd[WRITE]); | |
//point D | |
num = read (fileno(stdin), (void *) str, (size_t) sizeof (str)); | |
if (num > MAX) { | |
perror ("pipe read error\n"); | |
exit (1); | |
} | |
printf ("By %d: %s", getpid(), str); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment