在C中构建一个完整的双工管道

时间:2012-12-08 20:02:33

标签: c linux pipe

我正在尝试制作一个全双工管道,这是我家庭作业的一部分(事先告诉我)。 作业的范围远远大于这个管道,我只需要它就可以完成,所以我可以继续工作。我只在这里粘贴重要的代码,我没有粘贴整个代码。

#define READ_END 0
#define WRITE_END 1

int main()
{
    Folder* curFolder = (Folder*) malloc (sizeof(Folder));
    assert(curFolder != NULL);

    initFolder(curFolder, NULL, "root");
    makeDir(curFolder, "test");

    return 0;
}

Pipe* createPipe()
{
    Pipe* p = (Pipe*) malloc (sizeof(Pipe));
    assert(p != NULL);

    pipe( p->readPipe );
    pipe( p->writePipe );

    //close( p->readPipe[WRITE_END] );
    //close( p->writePipe[READ_END] );

    return p;
}

char* readMsg(FolderRef* folderHandle, char* buffer)
{
    read(folderHandle->pipe->readPipe[READ_END], buffer, PIPE_BUF);

    return buffer;
}

void sendMsg(FolderRef* folderHandle, char* msg)
{
    write(folderHandle->pipe->writePipe[WRITE_END], msg, strlen(msg) + 1);
}

void makeDir(Folder* curFolder, char* name)
{
    pid_t childId;
    char msg[PIPE_BUF];
    Pipe* con = createPipe();

    childId = fork();

    switch ( childId )
    {
        case -1: // error occurred
        {
            printf( "Error at fork in function makeDir.\n" );
            exit( 0 );
        }
        case 0: // son process
        {
            initFolder( curFolder, getFolderHandle( getppid(), con, "" ), name );
            readMsg(curFolder->parentFolder, msg);
            printf("%s\n", msg);
            sendMsg(curFolder->parentFolder, "roger roger");
            break;
        }
        default:
        {
            insertFolder(&curFolder->folderList, getFolderHandle(childId, con, name));
            sendMsg(curFolder->folderList->folder, "test");
            readMsg(curFolder->folderList->folder, msg);
            printf("%s\n", msg);
            break;
        }
    }
}

结果(现在)应该在屏幕上输出: 测试 罗杰罗杰

然而,我无法完成它。我好像错过了一些小细节。

1 个答案:

答案 0 :(得分:3)

如果您写信至pipe->writePipe[WRITE_END],则需要阅读pipe->writePipe[READ_END]。您似乎尝试从pipe->readPipe[READ_END]读取,但这是另一个管道。