NP Assignment 2
unknown
c_cpp
2 years ago
2.1 kB
9
Indexable
#include<stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> #include<stdlib.h> #define READ 0 #define WRITE 1 int main() { int fd1[2], fd2[2]; pipe(fd1), pipe(fd2); //process creates 2 pipes pid_t ret = fork(); //process forks //Both processes display their ids if(ret > 0) { printf("This is the parent process with ID %d\n", getpid()); //parent process identifies itself } else { printf("This is the child process with ID %d\n", getpid()); //child process identifies itself } //Both processes send messages if(ret > 0) { close(fd2[WRITE]), close(fd1[READ]); int parentMessage; //parent reads message from command line and sends to child printf("This is the parent with ID %d, enter the message to send to the child: ", getpid()); scanf("%d", &parentMessage); write(fd1[WRITE], &parentMessage, sizeof(int)); //parent sent the message to child close(fd1[WRITE]); int receivedMessage; int bytesRead = read(fd2[READ], &receivedMessage, sizeof(int)); printf("This is the parent with ID %d, Read %d bytes: %d \n", getpid(), bytesRead, receivedMessage); close(fd2[READ]); wait(0); exit(0); //parent exits } else { close(fd1[WRITE]), close(fd2[READ]); //child reads it's process ID and received integer int receivedMessage; int bytesRead = read(fd1[READ], &receivedMessage, sizeof(int)); printf("This is the child with ID %d, Read %d bytes: %d \n", getpid(), bytesRead, receivedMessage); close(fd1[READ]); //child reads message from command line and sends to parent int childMessage; printf("This is the child with ID %d, enter the message to send to the parent: ", getpid()); scanf("%d", &childMessage); write(fd2[WRITE], &childMessage, sizeof(childMessage)); //child sent the message to parent close(fd2[WRITE]); exit(0); //child process exits } return 0; }
Editor is loading...