我的目标是通过 FIFO 在孩子和父母之间建立 IPC。孩子应该跑
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;
}
main 目前只创建fifo(mkfifo)、forks()并调用函数。我的问题可能与父级的标准输入(运行剪切)有关,但我不这么认为,或者我假设 execl() 直接从标准输入读取而它没有。我认为这真的是因为我没有正确地通过 execl() 编写“剪切”。
对代码的任何更正,甚至我表达某些想法的方式都可能表明我没有正确理解某些内容,我们将不胜感激。感谢您的帮助