-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;
}

パイプを使用しない場合にファイルへの書き込みが機能することはわかっていますが、今では無限ループが発生しており、何が問題なのかわかりません。

4

1 に答える 1

-1

私はそれを考え出した!小さなことがすべての違いを生むのはおかしい。

于 2013-02-01T04:52:22.500 に答える