Created
June 12, 2016 13:24
-
-
Save Lessica/2d765f0eb39394d4c84f25b6f7d70352 to your computer and use it in GitHub Desktop.
Operating System Pipe Testing Demo 2
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 <fcntl.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <ctype.h> | |
int main(int argc, char *argv[]) | |
{ | |
int fd[2]; | |
char buffer[80]; | |
fd[1] = open("hole", O_CREAT | O_WRONLY, S_IRWXU | S_IRWXG); | |
fd[0] = open("hole", O_RDONLY, S_IRWXU | S_IRWXG); | |
// pipe(fd); | |
char str1[80]; | |
char str2[80]; | |
int pid1, pid2, I; | |
while ( ( pid1 = fork() ) == -1 ); | |
if ( pid1 == 0 ) | |
{ | |
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 ) | |
{ | |
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