【发布时间】: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 肯定是导致问题的原因。