【发布时间】:2016-04-11 21:08:58
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
int main(void) {
if(mkfifo("fifo", S_IRWXU) < 0 && errno != EEXIST) {
perror("Fifo error");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if(pid == 0) /*dziecko*/
{
int fifo_write_end = open("fifo", O_WRONLY);
if(fifo_write_end < 0)
{
perror("fifo_write_end error");
exit(EXIT_FAILURE);
}
if(dup2(fifo_write_end, STDOUT_FILENO) < 0)
{
perror("dup2 fifo_write_end error");
exit(EXIT_FAILURE);
}
if(execlp("/bin/ls", "ls", "-al", NULL) < 0)
{
perror("execlp error");
exit(EXIT_FAILURE);
}
}
if(pid > 0) /*rodzic*/
{
int fifo_read_end = open("fifo", O_RDONLY);
if(fifo_read_end < 0)
{
perror("fifo_read_end error");
exit(EXIT_FAILURE);
}
if(dup2(fifo_read_end, STDOUT_FILENO) < 0)
{
perror("dup2 fifo_read_end error");
exit(EXIT_FAILURE);
}
int atxt = open("a.txt", O_WRONLY|O_CREAT, S_IRWXU);
if(atxt < 0)
{
perror("a.txt open error");
exit(EXIT_FAILURE);
}
if(dup2(atxt,STDOUT_FILENO) < 0)
{
perror("dup2 atxt error");
exit(EXIT_FAILURE);
}
if(execlp("/usr/bin/tr", "tr", "a-z", "A-Z", NULL) < 0)
{
perror("tr exec error");
exit(EXIT_FAILURE);
}
}
if(pid < 0)
{
perror("Fork error");
exit(EXIT_FAILURE);
}
return 0;
}
程序不会停止。我不知道为什么 。它应该执行 ls -al | tr a-z A-Z 并将其写入文件 a.txt。
如果有人可以,请解释一下如何使用 ls-al | tr a-z A-Z | tr A-Z a-z > a.txt 。对于另一个 tr,我需要第二个 mkfifo 对吗?我不确定它是如何工作的,我是否应该在此处关闭写入或读取描述符。使用“管道”时,它是 nesesery。
感谢您的帮助!
【问题讨论】: