【问题标题】:Two way communication from the file that run with exec in child来自在子进程中与 exec 一起运行的文件的两种方式通信
【发布时间】:2020-03-15 01:20:08
【问题描述】:

我正在程序 y 中创建一个带有 fork 的子进程。在那个孩子身上,我用 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;
}

【问题讨论】:

    标签: c operating-system pipe fork exec


    【解决方案1】:

    您唯一可以直接传递的是孩子的退出代码(通过wait())。

    要在两个进程之间传递字符串,您需要像管道一样的 IPC 数据结构。请参阅unistd.h 中的pipe() 函数。

    【讨论】:

    • 我实际上正在使用管道,例如pipe(fd)。还是我错了?
    • 是的。但是你不要在子进程中使用管道。
    • 如何在我的孩子和程序 x 之间打开管道,我想应该是我的问题
    • 管道已经打开;你从父母那里继承它。你只需要给它写信。
    【解决方案2】:

    对于从孩子到父母的单向通信的简单情况),您可以使用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' 结果是执行程序的退出代码。

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2019-05-10
      相关资源
      最近更新 更多