【问题标题】:Reading and writing into the same file using a named pipe in C在 C 中使用命名管道读取和写入同一个文件
【发布时间】:2020-10-23 22:49:27
【问题描述】:

更具体地说,该程序应该模拟 bash 命令cat file| grep $keyword > file。 我所做的是:在父级中,我从文件中读取每个字符并将它们格式化为行,然后发送到命名管道,然后在子级中将包含关键字的行写入原始文件。

但是,我在尝试从原始文件中读取第二个字符时收到分段错误错误,我认为这是因为父级正在等待子级写入原始文件而不是读取所述内容文件。

任何关于错误发生原因的实施/解释的帮助都会很棒。

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

char key[20], *c,line[40];
int fd,fd_r,fd_w,fd_fr,fd_fw,counter=0;

int main(){

pid_t pid;
mkfifo("fifo1",0777);
fgets(key,10,stdin);

int k=0;

if ((pid=fork()) < 0)
        perror("err_fork");

if(pid){ //PARENT

        printf("%d\n",fd_r=open("prog.c",O_RDONLY));
        printf("%d\n",fd_fw=open("fifo1",O_WRONLY));
        while(read(fd_r,c,1)){
                line[k++]=(*c);
                while(read(fd_r,c,1) && ((*c)!='\n'))
                        line[k++]=(*c);
                line[k]=0;
                write(fd_fw,line,strlen(line)+1);
                memset(line,0,sizeof(line));
        }
        close(fd_r);
        close(fd_fw);
}
else{   //CHILD
        printf("%d\n",fd_w=open("prog.c",O_WRONLY));
        printf("%d\n",fd_fr=open("fifo1",O_RDONLY));
        while(read(fd_fr,line,sizeof(line))){
                c=strstr(line,key);
                if(c)
                        write(fd_w,line,strlen(line)+1);
        }
        close(fd_w);
        close(fd_fr);
}

unlink("fifo1");
}

【问题讨论】:

  • 你知道 bash 命令cat file| grep $keyword &gt; file 根本行不通吗?通常它只会截断文件。如果你真的想要,我想你可以模仿它的破碎,但有什么意义呢?
  • 另外,while(read(...)) 不是解决问题的好方法,因为在发生错误的情况下,read() 返回-1,它是非零的,因此会导致循环继续,即使c 不包含新数据。
  • 如果不需要区分error和EOF,可以使用while (read(...) &gt; 0)
  • 孩子需要在关闭文件之前截断文件。否则,文件末尾仍有未被覆盖的行。
  • @NateEldredge 这并没有模拟这种损坏,因为它在打开输出文件时不使用O_TRUNC

标签: c linux bash


【解决方案1】:

您在尝试将一个字节读入c,因此出现了段错误。然而,c 是一个未初始化的全局指针,因此它等于NULL。因此,尝试在该位置读取数据是对内存的无效使用。

你要做的是声明

char c;

然后

read(fd_r,&c,1)

【讨论】:

  • 嗯,它是全局的,所以它被初始化为 NULL。但确实,你读不进去。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多