在exec中将管道作为参数传递 [英] Passing a pipe as a parameter in exec

查看:200
本文介绍了在exec中将管道作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将管道传递给我用execv创建的另一个进程.到目前为止,这是我的代码,但是没有用.我到处都在寻找信息,但是我找不到关于传递pipe vie exec的任何东西.任何帮助表示赞赏.谢谢

I'm trying to pass a pipe to another process, which I create with execv. This is my code so far, but it doesn't work. I've looked everywhere for information, but I can't find anything specifically about passing a pipe vie exec. Any help is appreciated. Thanks

int fd[2];
pipe(fd);

char passwrite[1];
sprintf(passwrite, "%d", fd[0]);

char arg[1];
arg[1]=passwrite;

int x;
x=fork();
if (x==0) {
execv("NewProg",arg);
}

推荐答案

即使在您开始进行管道处理之前,代码也有一些潜在的问题(请参见

There are a couple of potential problems with your code, even before you get to the pipe handling (see Jonathan Leffler's answer for that). First, you need a larger buffer, since a single character isn't enough to hold an integer and the terminating NUL:

char passwrite[10];

然后,arg必须是一个指针数组,而不是字符数组,并且还必须更大:

Then, arg needs to be an array of pointers, not an array of characters, and it also needs to be bigger:

char *arg[3];

您需要在args中放入特定内容:

You need to put specific things in the args:

arg[0] = "NewProg"; // name of program
arg[1] = passwrite;
arg[2] = NULL;

我系统上execv的手册页对此进行了详细说明:

The man page for execv on my system explains this in more detail:

execl(),execlp()和execle()函数中的const char * arg及随后的省略号可以认为是arg0,arg1,...,argn.它们一起描述了一个或多个指向以null终止的字符串的指针的列表,这些字符串表示可用于已执行程序的参数列表.按照惯例,第一个参数应指向与正在执行的文件关联的文件名.参数列表必须以NULL指针终止,并且由于它们是可变参数函数,因此必须将该指针强制转换为(char *)NULL.

The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

这篇关于在exec中将管道作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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