-1
我有一些东西我一直在大部分时间都在盯着,并且无法弄清楚。我正在用C编写代码,它应该使用管道来回传递一个字节,从而允许我在父进程和子进程之间切换,这将会轮流将一个字符串写入文件。这里是我的代码:使用管道同步进程之间的文件写入
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd[2];
int fd2[2];
char token = 'a';
int file = open("output.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
if (pipe(fd) == -1 || pipe(fd) == -1)
{
printf("Pipe failed");
return(-1);
}
pipe(fd2);
int pid = fork();
int i;
int j;
write(fd[1], token, 1);
if (pid) // Parent enters here
{
for (i = 0; i < 100;)
{
if (read(fd[0], token, 1) != -1)
{
write(file, "ppppppp", 7);
i++;
write(fd2[1], token, 1);
}
//usleep(500000);
}
wait();
}
else if (pid == 0) // Child enters here
{
for (j = 0; j < 100;)
{
if (read(fd2[0], token, 1) != -1)
{
write(file, "ccccc", 5);
j++;
write(fd[1], token, 1);
}
//usleep(500000);
}
}
else // Error creating child
{
exit (-1);
}
close(file);
return 0;
}
我知道当我不使用管道写入文件的工作,但现在我发现了一个无限循环,我不知道是什么问题。
要么在答案中提供解决方案,要么删除问题。 –
我没有看到任何新行或fflush()调用将输出转储到文件.... –