我正在尝试通过 fifo 将 file1 的内容复制到其他 file2 中。我想在fifo中写回前四个字符(在读取期间,而不是在将内容从file1写入fifo时更早),然后也将其复制到file2中。但是前四个字符不会附加在后面,而是随机插入到中间。我的代码是
int main( int argc, char* argv[] ) {
int fdes,fdes1;
pid_t pid;
ssize_t numRead;
char readBuff[1];
char writeBuff[1];
int readCounter;
int c=0;
umask(0);
if (mkfifo("ajjp.e",0666) == -1 /*make the fifo*/
&& errno != EEXIST)
{}
if( argc < 3 ) {
printf( "Atleast need 2 params " );
exit(1);
}
int to_copy = open( argv[1], 0 );/* file from which contents are to be copied */
int oo = creat(argv[2], 0666);/* file created where we've to write contents*/
if ( to_copy == -1 ) {
printf( "Opening file failed " );
exit(1);
}
if ( (pid = fork()) < 0) /* child process is made*/
perror("fork error");
/* in parent process,I'm cwriting contents of file1 to fifo character by character */
else if(pid>0)
{
fdes = open("ajjp.e", O_WRONLY);
while( (readCounter = read( to_copy, readBuff, sizeof( readBuff ) ) > 0 ) ) {
write( fdes, readBuff, sizeof( readBuff ) );
}
close(to_copy);
}
/* now, in child process, I opened its read end then I'm reading contents from fifo and writing it to file2(i.e copy_to here) but for first four characters( c< 5 here), I'm writing them to fifo also by opening its write end. */
else
{
fdes1 = open("ajjp.e", O_RDONLY);
fdes = open("ajjp.e", O_WRONLY);
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
printf("signal");
int copy_to = open( argv[2], 0666);/* opened the file where we've to write*/
if ( copy_to == -1 ) {
printf( "Opening file failed " );
exit(1);
}
for(;;) {
c++;
numRead = read(fdes1, readBuff, sizeof(readBuff));/* reading from read end of fifo*/
if (numRead == 0)
break;
/* write to the file2*/
if (write(copy_to, readBuff, numRead) != numRead)
{}
/* for first 4 characters, I am rewriting to the back of fifo*/
if(c<5)
{
write(fdes,readBuff,sizeof(readBuff));
}
/*after writing those 4 characters, write end I've closed*/
if(c==5)
close(fdes);
}
close(fdes);
close(fdes1);
}//end else
return 0;
}
现在,如果在终端上,我运行
$ ./a.out a.txt b.txt
我想从 a.txt 复制到 b.txt,b.txt 包含 a.txt 加上在字符之间随机插入的前 4 个字符。