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

标签 c operating-system pipe fork exec

我正在程序 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/

相关文章:

将数组内容从一个复制到另一个(动态内存分配)

c++ - 什么是应用足迹以及如何计算它?

memory - 将相同的物理地址映射到不同的虚拟地址空间

assembly - 如何制作可引导的 iso(不是 cd 或闪存驱动器)来测试您自己的引导加载程序?

stream - pipe()将如何在节点js中执行读写操作?

c - 帮助阅读 C 语言中的基本用户输入

c - 传感器故障。更换 Arduino Wire 库时遇到问题

c - 通过管道将 C 程序输入传递给 system() 函数 fuinput

c - 在 C 中使用不同的字符串?

连接套接字和 FIFO 管道