C – fork() and execlp(), printf before execlp() is not executed

fork() and execlp(), printf before execlp() is not executed… here is a solution to the problem.

fork() and execlp(), printf before execlp() is not executed

I’m learning inter-process communication… This is the code that annoys 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 nothing is executed after execlp(), but my printf() statements precede execlp(), so why are they not executed?

2) The program acts as a pipe command in Linux
So it’s like “ls | wc -l” executes like “l”, but how does the system know like “ls | wc -l” instead of “wc -l | ls” executes the program like that: ??

3) I

think the problem with 2) is because I turned off the standard output and used it as my pfds[1] and turned off the standard input and used it as my pad [0]: But what if one thread exits before another: ??

4) (I use both Xcode and gcc), when running the above program in gcc it works fine, but when running in Xcode it shows “SIGTRAP” and returns “1” in the console

PLZ help….

PS: It would be better if someone told me how to see the execution of a separate thread in any general issue!!
Thank you!!

Solution

  1. Your printf is executing. However, it will only refresh after you redirect stdout, so its output will not appear on the terminal. If you want to see it on stderr, try using fprintf(stderr, ...), or try fflush(stdout) before you start messing around with file descriptors.

  2. You attach the write side of the pipe to the standard output of the ls process and the read end to the standard input on the WC, so there is no confusion.

  3. I’m not sure what you care about. The ls process exits when it finishes listing directories, while wc exits after running out of input and printing lines. Once both processes holding the endpoint close it (by exiting), the pipeline is automatically cleaned up.

  4. Hardly. What does the debugger show? However, the Xcode debugging environment is primarily used to develop and debug desktop/mobile applications, so it might just be a fluke.

Related Problems and Solutions