我正在尝试通过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个字符。
答案 0 :(得分:0)
您遇到了一些逻辑问题和同步问题。你的目标不太明确,但似乎你想要复制一个文件,比如说“Hello World”,在副本中,它应该有“Hello World”,但也有“Hell”。所以,也许是“HelHleo” llWorld“?
计算机速度快,可以缓冲并一次完成很多工作。您的子进程可能甚至在父进程完成之后才会执行,因为它需要一些时间来启动新进程。因此,你可能会得到“Hello WorldHell”。也就是说,在孩子开始阅读之前,父母完全将文件复制到FIFO。您需要研究一些同步方法。例如,使用您拥有的工具,您可以制作另一个fifo。让父母等到可以从中读取。让孩子在加载时写入它,作为告诉父母准备好的方式。使您的文件非常大也可能让孩子有时间在每个角色后面开始或添加睡眠语句。
如果您提供了输入文件以及输出(输出错误),那么推测会更容易。但是,基本上,您有一个多进程/多线程问题,您希望它们一起运行,但它们最终会一次运行一个。减慢父母的速度或使其等待孩子。