Last active
February 9, 2024 01:52
-
-
Save dulimarta/c6f4b3925fff0ea2ed6d to your computer and use it in GitHub Desktop.
CS452 Lab04 - Pipes - Sample 1
This file contains hidden or 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> | |
#include <error.h> | |
#define READ 0 | |
#define WRITE 1 | |
#define MAX 1024 | |
int main () { | |
int fd[2]; | |
size_t num, len; | |
pid_t pid; | |
char str[MAX]; | |
if (pipe (fd) < 0) { | |
perror ("plumbing problem"); | |
exit (1); | |
} | |
printf("Pipe descriptors: read=%d write=%d\n", fd[0], fd[1]); | |
// point A | |
if ((pid = fork ()) < 0) { | |
perror ("fork failed"); | |
exit (1); | |
} | |
// point B | |
else if (pid == 0) { | |
close (fd[READ]); | |
//point C | |
printf ("Type a sentence: "); | |
fgets (str, MAX, stdin); | |
printf ("Sent by %d: %s", getpid(), str); | |
len = strlen(str) + 1; | |
write (fd[WRITE], &len, sizeof(len)); | |
write (fd[WRITE], (const void *) str, (size_t) len); | |
exit (0); | |
} | |
close (fd[WRITE]); | |
//point C | |
read(fd[READ], &len, sizeof(len)); | |
perror ("pipe read string length\n"); | |
num = read (fd[READ], (void *) str, len); | |
perror ("pipe read string\n"); | |
if (num != len) { | |
exit (1); | |
} | |
printf ("Received 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