我想說這個事實,我沒有正式的使用pipes
的教育,所以這是我第一次冒險。更何況,我無法找到任何類似的問題,我的情況。C Unix - fork(),execl()和管道在一個循環中
注:這是一個較大的學校任務項目的一部分,所以我不要求任何人爲我這樣做。我只想要一些方向/有用的代碼段。 (我試圖使這一儘可能通用,以避免出現「騙子」的言論。)
我試圖運行for-loop
超過int k
元素在父進程生成關閉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是否成功,並檢查讀取是否返回0或-1,如果-1檢查errno。 – 2013-02-21 05:53:03
該execl肯定是造成這個問題。 – MrHappyAsthma 2013-02-21 05:59:18