简体   繁体   English

传递文件描述符 - 执行(类型转换)

[英]Pass File Descriptor - Execve (typecast)

I am wondering how I can pass a file descriptor through the execve() command and then access it on the other side. 我想知道如何通过execve()命令传递文件描述符,然后在另一端访问它。 I know that I can use dup2 to redirect the file-descriptor but I cannot do that. 我知道我可以使用dup2重定向文件描述符,但我不能这样做。 I am required to actually pass the file descriptor to the child and use it in the child. 我需要实际将文件描述符传递给子进程并在子进程中使用它。

What I have done so far: 到目前为止我做了什么:

Parent makes pipe + args like the following: Parent生成pipe + args,如下所示:

int pfd[2];
if(pipe(pfd) == -1)
    exitWithError("PIPE FAILED", 1);
char *args_1[] = {"reader", argv[1], (char*) pfd, (char *) 0};

Then the child calls execve after fork() like the following: 然后孩子在fork()之后调用execve ,如下所示:

close(pfd[1]);
execve("./reader", args_1, NULL);

Then, in the reader program I try to access pipe descriptor that was passed: 然后,在读者程序中,我尝试访问传递的管道描述符:

int main(int argc, char* argv[]){
    ...
    write(argv[2][1], buf, read_test);

argv[2] should be referencing the pipe descriptor, then the argv[1] should go to the write end of the pipe. argv[2]应该引用管道描述符,然后argv[1]应该转到管道的写端。 I am almost positive that I need to do some type-casting differently here, but everything I try doesn't quite work out. 我几乎肯定我需要在这里做一些不同的类型转换,但我尝试的一切都不太合适。

NOTE : I have a working version of this program using dup2 to redirect to stdin and stdout for the children, but I have to actually pass the pipe descriptor to a child as per instructions of the project. 注意 :我有一个这个程序的工作版本,使用dup2重定向到孩子们的stdinstdout ,但是我必须按照项目的指示将管道描述符传递给子节点。

Any help is appreciated. 任何帮助表示赞赏。

Simply casting the file descriptor to a char* isn't a good idea. 简单地将文件描述符转换为char*并不是一个好主意。 It could cause data loss if the OS chooses to copy the strings and stops at the 0 bytes, so the data isn't entirely copied. 如果操作系统选择复制字符串并停止在0字节,则可能导致数据丢失,因此数据不会完全复制。 It would be safer to create a string containing the file descriptor. 创建包含文件描述符的字符串会更安全。

int pfd[2];
if(pipe(pfd) == -1)
    exitWithError("PIPE FAILED", 1);
char string1[12]; // A 32 bit number can't take more than 11 characters, + a terminating 0
snprintf(string1,12,"%i",pfd[1]); // Copy the file descriptor into a string
char *args_1[] = {"reader", argv[1], &string1[0], (char *) 0};

The reader program then uses atoi to convert this back into an int. 读者程序然后使用atoi将其转换回int。

int fd = atoi(argv[2]);
write(fd,buf,read_test);

If you really want to use a cast, then you need to cast argv[2] as int* in your reader. 如果你真的想使用强制转换,那么你需要在你的读者中将argv[2]int*

write(((int*)argv[2])[1],buf,read_test);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM