从与子级中的exec一起运行的文件进行双向通信
我正在用程序y中的fork创建一个子进程。在该子程序中,我使用exec运行另一个程序,在该程序中,我希望该程序中的函数(我们称之为program x)向我返回一些东西。是否有方法将此返回值传递给父级? 我提供了某种伪代码,演示了我下面要做的事情 程序x:从与子级中的exec一起运行的文件进行双向通信,c,operating-system,pipe,fork,exec,C,Operating System,Pipe,Fork,Exec,我正在用程序y中的fork创建一个子进程。在该子程序中,我使用exec运行另一个程序,在该程序中,我希望该程序中的函数(我们称之为program x)向我返回一些东西。是否有方法将此返回值传递给父级? 我提供了某种伪代码,演示了我下面要做的事情 程序x: int main(int argc, char** argv) { if(argc != 2) { printf("argument count does not match\n"); retu
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("argument count does not match\n");
return -1;
}
printf("task1!\n");
...
char *value = "want this"; // how to pass this to the parent in the program y?
...
}
程序y:
int main(int argc, char *argv[])
{
int fd[2];
pipe(fd);
pid_t p;
p = fork();
if(p==-1)
{
printf("There is an error while calling fork()");
}
if(p==0)
{
printf("We are in the child process\n");
printf("Calling hello.c from child process\n");
char *args[] = {"Hello", "C", "Programming", NULL};
execv("./hello", args);
close(fd[0]);
write(fd[1], ???, ??);
close(fd[0]);
}
else
{
printf("We are in the parent process");
wait(NULL);
close(fd[1]);
read(fd[0], ???,???);
close(fd[0]);
}
return 0;
}
唯一可以直接传递的是子级的退出代码(通过
wait()
)
要在两个进程之间传递字符串,需要像管道一样的IPC数据结构。请参见
unistd.h中的pipe()
函数了解从孩子到家长的单向通信的简单情况),您可以使用popen
。它的级别高,使用简单,与fork/exec相比,开销很小(如果有的话)
int main(...)
{
...
FILE *fp = popen("./hello 'Hello', 'C', 'Programming'", "r") ;
char resp[200] ;
if ( fgets(resp, sizeof(resp, fp) ) {
// Do something
}
int result = pclose(fp) ;
}
请注意,传递命令行参数的方法遵循shell规则-可能需要引用参数(通常是单引号)才能传递任何特殊字符
“pclose”结果是执行程序的退出代码。我实际上使用的是管道,比如pipe(fd)
。还是我错了?没错。但是你不能在子进程中使用管道。我怎样才能打开我的孩子和程序x之间的管道,这应该是我的问题,我想管道已经打开了;您从父级继承它。你只要给它写信就行了。