Question

I m learning interprocess communication ...this is the code that bugs me

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
   int pfds[2];
   pipe(pfds);
    if (!fork()) 
    {
       printf("I m the child process\n");
       close(1);  /* close normal stdout */
       dup(pfds[1]);  /* make stdout same as pfds[1] */


       close(pfds[0]); /* we don't need this */
       execlp("ls", "ls", NULL);
 } 
 else 
 {
    printf("I m the parent process\n");
    close(0);       /* close normal stdin */
    dup(pfds[0]);   /* make stdin same as pfds[0] */
    close(pfds[1]); /* we don't need this */
    execlp("wc", "wc", "-l", NULL);
 }
  return 0; 

}

These are some of the questions :- 1) I agree that after the execlp() , nothing gets executed , but my printf() statements are before the execlp() , then still why they does not get executed ??

2)The program acts as a pipe command in linux hence it executes like "ls | wc -l" , but how does the system knows to execute the program like "ls | wc -l" and not "wc -l | ls" .. ??

3) I think the 2) question is because i have closed the stdout and used it as my pfds[1] and closed the stdin and used as my pads[0]..but what if the one threads gets exited before the other .. ??

4) (i m using Xcode as well as gcc) , when run the above program in gcc , it works well , but when run in Xcode it shows a "SIGTRAP" and returns "1" in the console

PLZ HELP ...

PS : It would be better if someone tell me how to see execution of the seperate threads in any general problem !! thank you !!

Was it helpful?

Solution

  1. Your printf is being executed. However, it only gets flushed after you redirect stdout, so its output is not shown on the terminal. Try fprintf(stderr, ...) if you want to see it on stderr, or fflush(stdout) before you start messing with file descriptors.

  2. You attach the writing end of the pipe to the stdout of the ls process, and the reading end to stdin on wc, so there's no confusion.

  3. I'm not sure what your concern is here. The ls process exits once it finishes listing the directory, and wc exits once it runs out of input and prints the number of lines. The pipe gets cleaned up automatically once both processes which hold an endpoint have closed it (by exiting).

  4. Hard to say. What does the debugger show? The Xcode debugging environment is primarily aimed at developing and debugging desktop/mobile applications, though, so it's probably just a fluke of some sort.

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