gpt4 book ai didi

C - mkfifo , ls - 不要停止

转载 作者:行者123 更新时间:2023-11-30 19:12:43 24 4
gpt4 key购买 nike

#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 | t a-z A-Z | t a-z A-Z | tr A-Z a-z > a.txt 。对于另一个 tr 我需要第二个 mkfifo 对吗?我不确定它是如何工作的以及我是否应该在此处关闭写入或读取描述符。对于“管道”,它是 nesery。

感谢您的帮助!

最佳答案

在管道关闭之前,管道的读取端不会报告 EOF。在所有引用它的描述符都关闭之前,管道不会关闭。调用 dup2 后,原始 FD 和您复制到的描述符都会引用该管道。您需要关闭原来的FD。

    if(dup2(fifo_write_end, STDOUT_FILENO) < 0)
{
perror("dup2 fifo_write_end error");
exit(EXIT_FAILURE);
}
close(fifo_write_end);
if(execlp("/bin/ls", "ls", "-al", NULL) < 0)
{
perror("execlp error");
exit(EXIT_FAILURE);
}

另一个问题是运行 tr 的进程需要将 FIFO 复制到 stdin,而不是 stdout。所以

    if(dup2(fifo_read_end, STDOUT_FILENO) < 0)
{
perror("dup2 fifo_read_end error");
exit(EXIT_FAILURE);
}

应该是

    if(dup2(fifo_read_end, STDIN_FILENO) < 0)
{
perror("dup2 fifo_read_end error");
exit(EXIT_FAILURE);
}

关于C - mkfifo , ls - 不要停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36559278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com