Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- int msg[2];
- const int MAX = 100;
- int main(int argc, char *argv[]) {
- int master, i, child, num, pid, ppid, counter, loops;
- char buffer[MAX];
- num = atoi(argv[1]);
- loops = atoi(argv[2]);
- counter = 0;
- master = (int)getpid();
- //check num arguments
- if (argc != 4) {
- fprintf(stderr, "%sn", "incorrect # arguments");
- }
- pipe(msg); //create pipe
- dup2(msg[0], STDIN_FILENO); //duplicate pipes
- dup2(msg[1], STDOUT_FILENO);
- close(msg[0]); //close ends of pipe
- close(msg[1]);
- //create other processes
- for(i=1; i<num; i++) {
- pipe(msg); //create new pipe
- //create new process
- child = fork(); //parent has child id
- pid = (int)getpid(); //has own pid
- ppid = (int)getppid(); //has parent pid
- //if parent, fix output
- if(child > 0){
- dup2(msg[1], STDOUT_FILENO);
- } else {
- dup2(msg[0], STDIN_FILENO);
- }
- close(msg[0]);
- close(msg[1]);
- if(child){
- break;
- }
- }
- //simple output
- fprintf(stderr, "process %d with id %d and parent id %dn", i, pid, ppid);
- //message passing
- //if master, establish trasnfer
- if (pid == master) {
- //parent
- close(msg[0]); //closes its read end
- char buffer[MAX];
- fprintf(stderr, "Parent: Waiting for inputn");
- while(1) {
- scanf("%s", buffer);
- if (strcmp(buffer, "exit")==0) {
- break;
- }
- write(msg[1], buffer, MAX);
- }
- close(msg[1]); //closes it write end
- } else {
- //child
- close(msg[1]); //closes its write end
- char buffer[MAX];
- fprintf(stderr, "Child: Waiting for pipen");
- while(read(msg[0], buffer, MAX) > 0) {
- fprintf(stderr, "Received: %sn", buffer);
- buffer[0] = '