Question

i have a homework for my university in which i must have a main process and 3 child processes. I must read an expression in the main process from the user and then pass it through an anonymous pipe at p1 process with redirection of standard input. Then i must modify it and pass it with another pipe to p2. Then the same thing happens with p3 with another pipe. Finally i must return the final expression from p3 to main process using another pipe. When i create p1,p2,p3 processes in the main process by calling fork, i use execlp to run the code of each of these process.

What i managed to do until now(apart from each process' logic which was really complicated), is to send the expression of the user from the main process to p1 process. Inside the code of p1 in the main process, i redirected to the input of the p1 to the read end of the first pipe and i successfully read the expression from main process.

My problem is with the other processes. I really got stuck on how to correctly redirect the inputs and outputs of each pipe to communicate with all processes. I really would appreciate any help here. Thank you in advance.

Was it helpful?

Solution

in this EXAMPLE you can see the execlp() function and the fork() function:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
   pid_t pid;
   char *pathvar;
   char newpath[1000];

   pathvar = getenv("PATH");
   strcpy(newpath, pathvar);
   strcat(newpath, ":u/userid/bin");
   setenv("PATH", newpath);

   if ((pid = fork()) == -1)
      perror("fork error");
   else if (pid == 0) {
      execlp("newShell", "newShell", NULL);
      printf("Return not expected. Must be an execlp error.n");
   }
}

Here you can see how to make a pipe between two process:

/*
 “ls -R | grep <pat>” where <pat> is a pattern
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv [])
{
    int pipe1[2];
    int pid1;
    int pid2;
    char stringa[100];

    pipe(pipe1); // creo la pipe

    if((pid1=fork())==0)
    {
        close(pipe1[0]);
        dup2(pipe1[1],1);
        close(pipe1[1]);
        execlp("ls","ls","-R",NULL);
    }

    if((pid2=fork())==0)
    {
        close(pipe1[1]);
        dup2(pipe1[0],0);
        close(pipe1[0]);
        execlp("grep","grep",argv[1],NULL); 
    }

    close(pipe1[0]);
    close(pipe1[1]);
    waitpid(pid1,NULL,0);
    waitpid(pid2,NULL,0);
    exit(0);

}

OTHER TIPS

From your description I think you want to chain forking. E.g. instead of having main fork three times to create p1, p2 and p3, instead let main fork once to create p1, then let p1 fork once to create p2 which also forks once to create p3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top