[英]What's wrong with my under-linux c prog: “ls -al | tr a-z A-Z > file.txt”?
我對linux還是很陌生。 我的腳本無法正常工作。 我只是在猜測,該程序在執行tr函數時被暫停。
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int pdesc[2];
pipe(pdesc);
int a = fork();
if (a == 0) // child
{
dup2(pdesc[1],1); // chaning std_out to pipes_out
execlp("ls", "ls", "-l", "-a", NULL);
}
else //parent
{
wait();
int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC,0777);
dup2(pdesc[0], 0); // chaning std_in to pipes_in
dup2(file1, 1); // chaning std_out to file's stream
execlp("tr", "tr", "a-z", "A-Z", NULL);
}
return 0;
}
經典錯誤,所以,很好的問題。
您需要關閉父級和子級中未使用的管道文件描述符。
從管道讀取的過程(本身)具有開放的管道寫端,因此管道永遠不會完全關閉,因此永遠不會傳遞EOF。
另外, wait(2)
導致死鎖,程序不包含<sys/wait.h>
,並且對wait(2)
的調用缺少必需的參數。 因為外殼程序將等待父級而不是子級完成,所以實際上在這里的某個地方調用wait(2)
會很好。 但是在當前的兩進程設計中,您無處可放,因為在父級的execlp(2)
之后您不受控制。 解決該問題的一種方法是再次使父fork()循環,並讓原始PID在循環中除了wait(2)之外什么都不做,直到所有子項都完成為止。
這是一個工作版本,還請注意對輸出文件模式的更改。
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int pdesc[2];
pipe(pdesc);
int a = fork();
if (a == 0) { // child
dup2(pdesc[1],1); // chaining std_out to pipes_out
close(pdesc[1]);
close(pdesc[0]);
execlp("ls", "ls", "-l", "-a", NULL);
} else { //parent
int file1 = open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
dup2(pdesc[0], 0); // chaning std_in to pipes_in
dup2(file1, 1); // chaning std_out to file's stream
close(pdesc[0]);
close(pdesc[1]);
close(file1);
execlp("tr", "tr", "a-z", "A-Z", NULL);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.