【问题标题】:C Unix - fork(), execl() and pipe in a loopC Unix - fork()、execl() 和循环中的管道
【发布时间】:2013-02-21 05:48:17
【问题描述】:

我想以我没有受过使用pipes 的正规教育作为开场白,所以这是我的第一次尝试。更不用说我找不到任何与我的情况类似的问题。

注意:这是一个更大的学校作业项目的一部分,所以我不要求任何人为我做这件事。我只想要一些方向/有用的代码段。 (我已尝试使其尽可能通用以避免“骗子”言论。)

我正在尝试在int k 元素上运行for-loop,其中父进程产生k 子进程与fork()execl(),然后使用pipe() 将输出发送回父母。这是我尝试使用的一些通用代码以及遇到的错误/问题:

注意:helloworld= 一个使用GCC 编译的可执行文件,生成printf("hello world\n");

int k = 10; //The number of children to make
int fd[2]; //Used for each pipe
int readFromMe[k]; //Holds the file IDs of each pipe fd[0]
int writeToMe[k]; //Holds the file IDs of each pipe fd[1]
int processID[k]; //Holds the list of child process IDs

//Create children
int i;
for(i = 0; i < k; i++)
{
    if(pipe(fd) == -1)
    {
        printf("Error - Pipe error.\n");
        exit(EXIT_FAILURE);
    }

    //Store the pipe ID
    readFromMe[i] = fd[0];
    writeToMe[i] = fd[1];

    if((processID[i] = fork()) == -1)
    {
        fprintf(stderr, "fork failure");
        exit(EXIT_FAILURE);
    }

    //If it is a child, change the STDOUT to the pipe-write file descriptor, and exec
    if(processID[i] == 0)
    {
        dup2 (writeToMe[i], STDOUT_FILENO);
        close(readFromMe[i]);

        execl("./helloworld", (char *)0);
    }

    //If it is the parent, just close the unnecessary pipe-write descriptor and continue itterating
    else
    {
        close(writeToMe[i]);
    }
}

//Buffer for output
char output[100000];

//Read from each pipe and print out the result  
for(i = 0; i < k; i++)
{
    int r = read(readFromMe[i], &output, (sizeof(char) * 100000));

    if(r > 0)
    {
        printf("result = %s\n", output);
    }

    close(readFromMe[i]);
}   

我的程序根本没有任何输出,所以我想弄清楚为什么会出现这个问题。

【问题讨论】:

  • 检查exec是否成功,检查read是否返回0或-1,如果-1检查errno。
  • execl 肯定是导致问题的原因。

标签: c unix exec fork pipe


【解决方案1】:

可能不相关,但您调用execl 错误。程序后面的额外参数是将argv 数组传递给其他程序main 函数。如您所知,它始终只有一个条目,即程序名称。所以你需要这样称呼它:

execl("./helloworld", "helloworld", NULL);

与你的问题更相关,你也应该检查错误,它实际上可能会失败。

【讨论】:

  • 它提到在其他问题中将“NULL”哨兵投射到(char *),这似乎并没有导致问题。我也更新了缺失的参数。谢谢:)
  • @MrHappyAsthma 不要更改问题以反映解决方案。令人困惑。
【解决方案2】:

尝试在打印输出函数中打印 'r' 的值。我怀疑读取返回的是您没有看到的错误(可能是 EPIPE)。此外,您的示例代码正在尝试 printf 'c',而不是像您想要的那样输出。

【讨论】:

  • 这是一个复制/粘贴错字,用“c”而不是“输出”。我不希望我的作业一字不差地发布到网上:P 但是在检查了“r”之后,事实证明这只是 execl 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多