[英]Reading and writing into the same file using a named pipe in C
更具體地說,該程序應該模擬 bash 命令cat file| grep $keyword > file
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");
}
您之所以出現段錯誤,是因為您試圖將一個字節讀入c
。 但是, c
是一個未初始化的全局指針,因此它等於NULL
。 因此,嘗試在該位置讀取數據是對內存的無效使用。
你做的是聲明
char c;
進而
read(fd_r,&c,1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.