gpt4 book ai didi

c - 在 fifo 中同时读取和写入(在后面)

转载 作者:行者123 更新时间:2023-11-30 17:22:31 25 4
gpt4 key购买 nike

我正在尝试通过 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个字符。

最佳答案

您遇到了一些逻辑问题和同步问题。你的目标不太清楚,但看起来你想复制一个文件,说“Hello World”,在副本中,它应该有“Hello World”,但也有“Hell”。所以,也许“HelHleo” llWorld”?

计算机速度很快,可以缓冲并同时执行大量操作。您的子进程甚至可能直到父进程完全完成后才执行,因为启动新进程需要一些时间。因此,您可能会收到“Hello WorldHell”。也就是说,在子进程开始读取之前,父进程将文件完全复制到 FIFO。您需要研究一些同步方法。例如,使用您拥有的工具,您可以制作另一个 fifo。让父进程等待,直到它可以读取它。让子进程在加载时对其进行写入,以告诉父进程它已准备就绪。让文件变得非常大也可能会给 child 时间来开始或在每个字符后添加 sleep 语句。

如果您提供了输入文件和输出(错误的输出),推测会更容易。但是,基本上,您遇到了一个多进程/多线程问题,您希望它们一起运行,但它们实际上最终一次运行一个。放慢 parent 的速度或让它等待 child 。

关于c - 在 fifo 中同时读取和写入(在后面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011474/

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