C Unix-fork()、execl()和管道在循环中



我想先说一句,我没有受过pipes使用方面的正规教育,所以这是我的第一次冒险。更不用说,我找不到任何与我的情况类似的问题。

注意:这是学校作业的一个更大项目的一部分,所以我不要求任何人为我做这件事。我只想要一些指导/有用的代码段。(为了避免"骗子"的言论,我尽量让它通用化。)

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

注:helloworld=使用GCC编译的可执行文件,可生成printf("hello worldn");

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 = %sn", output);
    }
    close(readFromMe[i]);
}   

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

可能不相关,但您错误地调用了execl。程序后面的额外参数是argv数组对其他程序main的作用。正如你所知,它总是有一个条目,程序名。所以你需要这样称呼它:

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

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

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

最新更新