gpt4 book ai didi

c - 来自在子进程中使用 exec 运行的文件的两种方式通信

转载 作者:行者123 更新时间:2023-11-30 16:10:12 24 4
gpt4 key购买 nike

我正在程序 y 中使用 fork 创建一个子进程。在那个 child 中,我使用 exec 运行另一个程序,其中我希望该程序中的函数(我们称之为程序 x)向我返回一些内容。有没有办法将这个返回值传递给父级?我提供了某种伪代码来演示我下面想要做的事情。

程序.x:


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() 函数。

关于c - 来自在子进程中使用 exec 运行的文件的两种方式通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58935451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com