두 번째 프로그램이 지원하는 경우 stdin에 파이프를 작성하는 것이 좋습니다. Fred가 주석에서 언급했듯이 많은 프로그램은 제공된 파일이 없거나 -
이 파일 이름으로 사용되는 경우 stdin을 읽습니다. 이 파일 이름을 취해야합니다, 당신이 리눅스를 사용하는 경우
,이 시도 : 파이프를 작성하고, 명령 행에 /dev/fd/<fd-number>
또는 /proc/self/fd/<fd-number>
를 전달합니다.
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pfd[2];
int rc;
if(pipe(pfd) < 0) {
perror("pipe");
return 1;
}
switch(fork()) {
case -1: // Error
perror("fork");
return 1;
case 0: { // Child
// Close the writing end of the pipe
close(pfd[1]);
// Create a filename that refers to reading end of pipe
std::ostringstream path;
path << "/proc/self/fd/" << pfd[0];
// Invoke the subject program. "cat" will do nicely.
execlp("/bin/cat", "cat", path.str().c_str(), (char*)0);
// If we got here, then something went wrong, then execlp failed
perror("exec");
return 1;
}
default: // Parent
// Close the reading end.
close(pfd[0]);
// Write to the pipe. Since "cat" is on the other end, expect to
// see "Hello, world" on your screen.
if (write(pfd[1], "Hello, world\n", 13) != 13)
perror("write");
// Signal "cat" that we are done writing
close(pfd[1]);
// Wait for "cat" to finish its business
if(wait(0) < 0)
perror("wait");
// Everything's okay
return 0;
}
}
수의 입력 파일로 다른 프로그램을 사용 표준 입력 : 여기 예로서
는 세계 안녕하세요 2.0? 그렇다면 아마도 파이프 만 통과 할 수 있습니다. –
시스템에서 사용할 수있는 다양한 [IPC] (http://en.wikipedia.org/wiki/Interprocess_communication) 메커니즘에 대해 읽었습니까? – dirkgently
@FredLarson 나는 그렇게 생각하지 않는다. 나는 * only *가 파일 이름을 시작 매개 변수로 취한다고 믿는다. – Drise