在调用 C 中的任何 exec 函数后,我可以在子进程中使用由 paren 进程打开的文件描述符吗?
Can I use a file descriptor opened by the paren process in the child after calling any exec function in C?
假设我有一个进程 p
使用文件描述符(例如未命名的管道)与其父进程 p1
.
通信
假设 p
调用 fork()
来创建一个子进程 c
,紧接着 fork()
调用 exec
家族函数之一。
默认情况下,即使使用 exec
,父项的文件描述符也会复制给子项。所以 c
应该能够与 p1
通信,让其父 p
打开一个文件描述符到 p1
。
如果对应于该文件描述符的变量仅在 p
(和 p1
)中定义,我如何在 c
子进程的 C 源代码中获取该文件描述符?
举个例子,下面是p
和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]);
}
现在 "execution/child/process"
有自己的源代码,我不能使用变量 fd
与 p1
通信,因为它没有定义,但文件描述符应该存在:所以如何引用并使用它?
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
.
是的。主要条件是文件描述符没有设置 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
)?
您可以 dup2()
将文件描述为 well-known 数字,例如标准输入 (0)、标准输出 (1) 或标准错误 (2),或其他一些parent 和 child 代码一致的数字。
您可以将文件描述符编号作为参数传递给 child。
您可以将数字写入一个文件,child 随后会从该文件中读取它。
作为前面的一个特例,你可以设置一个从parent到child的stdin的管道,并将数字发送到child 在管道上。
这些不是唯一的可能性,但我认为它们涵盖了所有最简单和最好的可能性。请注意,第一个是唯一不依赖 child.
合作的
假设我有一个进程 p
使用文件描述符(例如未命名的管道)与其父进程 p1
.
假设 p
调用 fork()
来创建一个子进程 c
,紧接着 fork()
调用 exec
家族函数之一。
默认情况下,即使使用 exec
,父项的文件描述符也会复制给子项。所以 c
应该能够与 p1
通信,让其父 p
打开一个文件描述符到 p1
。
如果对应于该文件描述符的变量仅在 p
(和 p1
)中定义,我如何在 c
子进程的 C 源代码中获取该文件描述符?
举个例子,下面是p
和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]);
}
现在 "execution/child/process"
有自己的源代码,我不能使用变量 fd
与 p1
通信,因为它没有定义,但文件描述符应该存在:所以如何引用并使用它?
By default parent's file descriptors are duplicated to the child even when using
exec
. Soc
should be able to communicate withp1
, having its parentp
opened a file descriptor top1
.
是的。主要条件是文件描述符没有设置 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 inp
(andp1
)?
您可以
dup2()
将文件描述为 well-known 数字,例如标准输入 (0)、标准输出 (1) 或标准错误 (2),或其他一些parent 和 child 代码一致的数字。您可以将文件描述符编号作为参数传递给 child。
您可以将数字写入一个文件,child 随后会从该文件中读取它。
作为前面的一个特例,你可以设置一个从parent到child的stdin的管道,并将数字发送到child 在管道上。
这些不是唯一的可能性,但我认为它们涵盖了所有最简单和最好的可能性。请注意,第一个是唯一不依赖 child.
合作的