我的目标是通过FIFO在孩子和父母之间建立IPC。孩子应该运行如何使用execl()函数通过cut命令来运行stdin?
execl ("/bin/cat", "cat", "/etc/passwd", (char *)0);
其输出重定向到家长输入和家长应该用这个命令:
cut -l : -f 1
和输出这命令行。
现在,我已经成功地链接了我的FIFO,并将我的子进程的输出重定向到了父进程的输入。我已经完成了多个测试,并且连接正常。问题是与execl剪切,应该看起来像这样:
execlp("/bin/cut", "cut", "-l:", "-f", "1", NULL);
但我很确定它不是。
int cut(){
//
int myfifo;
char buf[MAX_BUF];
printf("\nCut opening FIFO");
if((myfifo = open("/tmp/myfifo", O_RDONLY | O_TRUNC))<0){
perror("open FIFO at cut");
quit(EXIT_FAILURE);}
else{printf("\nCut has FIFO opened and is reading\n");}
//read(myfifo, buf, MAX_BUF); outputting buf goes as supposed to
if(dup2(myfifo, 0) < 0){
perror("dup2 at cut");
quit(EXIT_FAILURE);}
//read(STDIN_FILENO, buf, MAX_BUF);
close(myfifo);
execlp("/bin/cut", "cut", "-l:", "-f", "1", NULL);
//this is for testing buf, but i guess the program shouldn't even get here
printf("\nCut has received: %s\nAnd is closing FIFO", buf);
return -1;
}
int cat(){
int myfifo;
//OPEN FIFO
printf("\nCat opening FIFO");
if((myfifo = open("/tmp/myfifo", O_WRONLY | O_TRUNC))<0){
perror("open FIFO at cat");
quit(EXIT_FAILURE);
}
else{
printf("\nCat has opened FIFO");
//WRITE OUTPUT OF "cat \etc\passwd" TO FIFO
dup2(myfifo, 1);
execl ("/bin/cat", "cat", "/etc/passwd", (char *)0);
}
close(myfifo);
return 0;
}
当前主要只创建fifo(mkfifo),forks()并调用该函数。 我的问题可能与父(streak)的标准输入(运行切割),但我不这么认为,或者我假设execl()直接从标准输入读取,而事实并非如此。 我认为这是真的,因为我没有正确地通过execl()写“剪切”。
对代码的任何更正,甚至我表达一些想法的方式都可能表明我没有正确理解某些内容,将不胜感激。 感谢您的帮助
为什么使用FIFO或命名管道而不是普通的普通匿名管道? –
哪个版本的'cut'支持'-l'选项? GNU'cut'和BSD(Mac OS X)'cut'都没有。您似乎将其用作等效于“-d”选项(字段分隔符),这对读取密码文件有意义。另外,在你机器上的'/ bin'中是否被剪切?它在我的'/ usr/bin'中,这两个目录是不同的。 –