0
我目前的計劃:餡輸出通過管道,然後打印到控制檯
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#ifndef STD_IN
#define STD_IN 0
#endif
#ifndef STD_OUT
#define STD_OUT 1
#endif
int main(int argc, char *argv[]) {
int mypipe[2];
int pid;
if (pipe(mypipe)) return -1;
if ((pid = fork()) == -1) return -1;
else if (pid == 0) {
//child puts stuff in pipe
close(mypipe[0]);
dup2(mypipe[1], STD_OUT);
execlp("ls", "ls", "-l", NULL);
close(mypipe[1]);
} else {
//parent reads and prints from pipe
char buf[1024];
int bytes_read;
close(mypipe[1]);
while (bytes_read = read(mypipe[0], buf, 1024) > 0) {
write(STD_OUT, buf, bytes_read); //write from buf to STD_OUT
}
wait(NULL);
close(mypipe[0]);
}
return 0;
}
我想父(其他情況)從管道讀取和打印內容到控制檯。我不確定這在哪裏失敗,並且需要一些關於我做錯了什麼的指示。提前致謝!