在fork和exec之后在父级和子级之间共享文件描述符 [英] Share a file descriptor between parent and child after fork and exec

查看:205
本文介绍了在fork和exec之后在父级和子级之间共享文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux上有两个进程,即A& B. 我想与进程B共享进程A的文件描述符,现在我将其序列化为char*并将其传递给execl参数,但这不起作用.

I have two processes on Linux, A & B. I want to share the file descriptor from process A with process B, now I just serialize it to a char* and pass it to the execl parameters, but that doesn't work.

A.c看起来像这样:

A.c looks like this:

union descriptor{
    char c[sizeof(int)];
    int i;
} fd;
pid_t pid;

fd.i = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Perform other socket functions

pid = fork();
if(pid == 0){
    // Read data from socket
    if(execl("./B", fd.c, NULL) < 0){
        exit(EXIT_FAILURE);
    }else(
        exit(EXIT_SUCCESS);
    }
}else if(pid < 0){
    exit(EXIT_FAILURE);
}else{
    waitpid(pid, NULL, 0);
}

B.c看起来像这样:

B.c looks like this:

union descriptor{
    char c[sizeof(int)];
    int i;
} fd;

memcpy(&fd.c[0], argv[0], sizeof(int));

write(fd.i, "TEST", 4);
close(fd.i);

但这是行不通的,而且我真的不明白为什么不这样做.我该如何进行这项工作?如果可行,在forkexec之后在父子之间共享文件描述符的最佳解决方案吗?

But this doesn't work, and I don't really understand why not. How can I make this work? And if it works, is it the best solution to share a file descriptor between a parent and a child after a fork and a exec?

该问题与我提出的问题无关,这是由@OliCharlesworth指出的传递整数的错误方式引起的.请关闭此问题.

The problem is unrelated to the question I asked, it is caused by a wrong way of passing an integer as pointed out by @OliCharlesworth. Please close this question.

推荐答案

File descriptors are always passed between a parent and child process

当您fork一个进程时,在父级中打开的文件描述符(在fork()时)将隐式传递给子级.无需显式发送它们.

When you fork a process, the file descriptors that are open in the parent(at the time of fork()) are implicitly passed on to the child. There is no need to send them explicitly.

例如:

伪代码如下:

进行中 A :

fd = open_socket_or_file;
char str_fd[3];
str_fd[0]=fd;
str_fd[1]=fd;
str_fd[2]=0;
if(fork()==0)
{
     execl("./B",str_fd,NULL);
}

在子进程 B 中,您可以执行以下操作:

In the child process B you can do:

int fd = argv[1][0];
/* now do whatever you want with the fd...*/

如果过程不同,则需要显式传递文件描述符.通常使用UNIX域套接字完成此操作(如果您使用的是Linux Flavors).有关与此相关的代码,您可以参见此答案

In case the processes are different, you need to pass the file descriptor explicitly. This is generally done using UNIX-Domain Sockets(If you are using Linux Flavors). For code related to this, you can see this answer

这篇关于在fork和exec之后在父级和子级之间共享文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆