Skip to content

Instantly share code, notes, and snippets.

@Lessica
Created June 12, 2016 12:45
Show Gist options
  • Save Lessica/aedb36eca45f1a9e8e45514183db6c7f to your computer and use it in GitHub Desktop.
Save Lessica/aedb36eca45f1a9e8e45514183db6c7f to your computer and use it in GitHub Desktop.
Operating System Pipe Testing Demo
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int fd[2];
char buffer[80];
pipe(fd);
char str1[80];
char str2[80];
int pid1, pid2, I;
while ( ( pid1 = fork() ) == -1 );
if (pid1 == 0)
{
if (lockf(fd[1], F_TLOCK, 0) == -1)
{
perror(argv[0]);
exit(1);
}
lockf(fd[1], F_LOCK, 0);
printf("Child 1 Input String 1\n");
scanf("%s", str1);
write(fd[1], str1, sizeof(str1));
lockf(fd[1], F_ULOCK, 0);
return 0;
}
else {
while ( ( pid2 = fork() ) == -1 );
if (pid2 == 0)
{
if (lockf(fd[1], F_TLOCK, 0) == -1)
{
perror(argv[0]);
exit(1);
}
lockf(fd[1], F_LOCK, 0);
printf("Child 2 Input String 2\n");
scanf("%s", str2);
write(fd[1], str2, sizeof(str2));
lockf(fd[1], F_ULOCK, 0);
return 0;
}
else
{
if (waitpid(pid1, NULL, 0) == pid1)
{
read(fd[0], buffer, 80);
for (int i = 0; i < sizeof(str1); i++)
buffer[i] = toupper(buffer[i]);
printf("Parent == Child 1: %s\n", buffer);
}
else
printf("Waitpid 1 Error!");
if (waitpid(pid2, NULL, 0) == pid2)
{
read(fd[0], buffer, 80);
for (int i = 0; i < sizeof(str2); i++)
buffer[i] = tolower(buffer[i]);
printf("Parent == Child 2: %s\n", buffer);
}
else
printf("Waitpid 2 Error!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment