從我試圖實現的說明這個問題如下:管道輸入/輸出
Linux Pipes as Input and Output
How to send a simple string between two programs using pipes?
http://tldp.org/LDP/lpg/node11.html
我的問題是沿問題的線路: Linux Pipes as Input and Output,但更具體。
從本質上講,我試圖取代:
/directory/program <input.txt> output.txt
通過在C++的管道,以避免使用硬盤驅動器。這裏是我的代碼:
//LET THE PLUMBING BEGIN
int fd_p2c[2], fd_pFc[2], bytes_read;
// "p2c" = pipe_to_child, "pFc" = pipe_from_child (see above link)
pid_t childpid;
char readbuffer[80];
string program_name;// <---- includes program name + full path
string gulp_command;// <---- includes my line-by-line stdin for program execution
string receive_output = "";
pipe(fd_p2c);//create pipe-to-child
pipe(fd_pFc);//create pipe-from-child
childpid = fork();//create fork
if (childpid < 0)
{
cout << "Fork failed" << endl;
exit(-1);
}
else if (childpid == 0)
{
dup2(0,fd_p2c[0]);//close stdout & make read end of p2c into stdout
close(fd_p2c[0]);//close read end of p2c
close(fd_p2c[1]);//close write end of p2c
dup2(1,fd_pFc[1]);//close stdin & make read end of pFc into stdin
close(fd_pFc[1]);//close write end of pFc
close(fd_pFc[0]);//close read end of pFc
//Execute the required program
execl(program_name.c_str(),program_name.c_str(),(char *) 0);
exit(0);
}
else
{
close(fd_p2c[0]);//close read end of p2c
close(fd_pFc[1]);//close write end of pFc
//"Loop" - send all data to child on write end of p2c
write(fd_p2c[1], gulp_command.c_str(), (strlen(gulp_command.c_str())));
close(fd_p2c[1]);//close write end of p2c
//Loop - receive all data to child on read end of pFc
while (1)
{
bytes_read = read(fd_pFc[0], readbuffer, sizeof(readbuffer));
if (bytes_read <= 0)//if nothing read from buffer...
break;//...break loop
receive_output += readbuffer;//append data to string
}
close(fd_pFc[0]);//close read end of pFc
}
我絕對確定上述字符串已正確初始化。但是,有兩件事情對我來說沒有意義:
(1)我正在執行的程序報告「輸入文件爲空」。由於我不是用「<」調用程序,所以不應該期待輸入文件。相反,它應該期待鍵盤輸入。此外,它應該閱讀「gulp_command」中包含的文本。 (2)程序的報告(通過標準輸出提供)出現在終端中。這很奇怪,因爲這個管道的目的是將stdout傳送到我的字符串「receive_output」。但是由於它出現在屏幕上,這表明信息沒有通過管道正確傳遞給變量。如果我落實的if語句結尾以下,
cout << receive_output << endl;
我什麼也沒得到,彷彿字符串爲空。我感謝您能給我的任何幫助!
編輯:澄清
我的計劃目前使用文本文件的另一個程序進行通信。我的程序寫入一個由外部程序讀取的文本文件(例如input.txt)。該程序然後產生output.txt,這是我的程序讀取的。因此,它是這樣的:
my code -> input.txt -> program -> output.txt -> my code
因此,我的代碼目前使用,
system("program <input.txt> output.txt");
我想要替換使用管道這個過程。我想將我的輸入作爲標準輸入傳遞給程序,並讓我的代碼將該程序的標準輸出讀入字符串。
你的開始主張不明確。你聲明你想用''''''''''''''''''替換'/ directory/program output.txt'來避免文件系統訪問。但是你需要多個流程才能使管道變得明智。 (你可以在一個進程中使用管道,但通常沒有意義。)所以,你可能有'/ directory/program1 output.txt';這是有道理的(你可能以前使用過'/ directory/program1 intermediate.txt;/directory/program2 output.txt')。請澄清你的意圖。 –
好點。我編輯了這個問題。 –
作爲一個額外的澄清,我的目標基本上與您以前回答的問題(stackoverflow.com/questions/1734932/...)中的問題相同(很好的答案)。 –