user9102437
user9102437

Reputation: 742

How to use fork in C?

Here is the full code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
    char *command, *infile, *outfile;
    int wstatus;

    command = argv[1];
    infile = argv[2];
    outfile = argv[3];

    if (fork()) {
        wait(&wstatus);
        printf("Exit status: %d\n", WEXITSTATUS(wstatus));
    }
    else {
        close(0);
        open(infile, O_RDONLY);
        close(1);
        open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
        execlp(command, command, NULL);

    }

    return 0;
}


This code should fork and exec a command with both stdin and stdout redirection, then wait for it to terminate and printf WEXITSTATUS(wstatus) received. e.g. ./allredir hexdump out_of_ls dump_file.

So, I understand everything before fork(). But I have the following questions:

  1. As far as I understand, fork() clones the process, however I do not understand how it executes the command, because execlp should do that and code never reaches that part.
  2. I do not get how execlp works. Why do we send a command to it twice (execlp(command, command, NULL);)?
  3. How does execlp know where to redirect the output if we do not pass outfile nowhere.
  4. Why do we even need an infile if the command is already passed as the other argument?

Thank you for your answers in advance.

Upvotes: 3

Views: 161

Answers (1)

Tony Tannous
Tony Tannous

Reputation: 14876

  1. As far as I understand, fork() clones the process, however I do not understand how it executes the command, because execlp should do that and code never reaches that part.

Fork returns pid of child in parent space and 0 in new process space. The son process makes a call to execlp.

if (fork()) { 
    /* Parent process waits for child process */
}
else {
    /* Son process */
    execlp(command, command, NULL);
}

  1. I do not get how execlp works. Why do we send a command to it twice (execlp(command, command, NULL);)?

Read execlp man page and this thread

The first argument, by convention, should point to the filename associated with the file being executed.


  1. How does execlp know where to redirect the output if we do not pass outfile nowhere.

Redirection happens before by closing stdin and stdout file descriptors. And redirection happens by opening files which file descriptors will accommodate entries 0 and 1.

else {
    /* redirecting stdin */
    close(0); 
    open(infile, O_RDONLY);  

    /* redirecting stdout */
    close(1); 
    open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);

    execlp(command, command, NULL);
}

  1. Why do we even need an infile if the command is already passed as the other argument?

We can't tell what your program does without seeing the argument passed as command.

Upvotes: 4

Related Questions