roschach
roschach

Reputation: 9406

Can I use a file descriptor opened by the paren process in the child after calling any exec function in C?

Suppose I have a process p that uses a file descriptor, for example an unnamed pipe, to communicate to his parent process p1.

Suppose p calls fork() to create a child process c which right after the fork() calls one of the exec family function.

By default parent's file descriptors are duplicated to the child even when using exec. So c should be able to communicate with p1, having its parent p opened a file descriptor to p1.

How can I get that file descriptor in the C source code of c child process if the variable corresponding to that file descriptor is defined only in p (and p1)?

Just to give an example of what I mean, the following is the code for p and p1

//p1 process
int fd[2];
pipe(fd);
pid_t p_pid, c_pid;

p_pid = fork();
if(p_pid == 0) // p process
{
/* p_pid closes up input side of pipe */
    close(fd[0]);
    c_pid = fork();
    if (c_pid)==0 //c child process
    {
        exec("execution/child/process"...); 
    }
    else
    {
        ...// do p process parenting stuff      
    }

 }
 else
 {
     /* Parent p1 process closes up output side of pipe */
     close(fd[1]);
 }

Now the "execution/child/process" has its own source code and I cannot use the variable fd to communicate with p1 since it is not defined but the file descriptor should exist: so how to reference it and use it?

Upvotes: 0

Views: 390

Answers (1)

John Bollinger
John Bollinger

Reputation: 181932

By default parent's file descriptors are duplicated to the child even when using exec. So c should be able to communicate with p1, having its parent p opened a file descriptor to p1.

Yes. The main proviso is that the file descriptor is not set close-on-exec.

How can I get that file descriptor in the C source code of c child process if the variable corresponding to that file descriptor is defined only in p (and p1)?

  • You can dup2() the file descripor onto a well-known number, such as stdin's (0), stdout's (1), or stderr's (2), or some other number that parent and child code agree upon.

  • You can pass the file descriptor number to the child as an argument.

  • You can write the number to a file from which the child subsequently reads it.

  • As a special case of the previous, you can set up a pipe from the parent to the child's stdin, and send the number to the child over the pipe.

Those are not the only possibilities, but I think they cover all of the easiest and best ones. Note well that the first is the only one that does not depend on the cooperation of the child.

Upvotes: 1

Related Questions