简体   繁体   中英

building a full duplex pipe in C

I'm trying to make a full duplex pipe, it's a piece of my home work (i tell beforehand). The scope of the homework is much much larger than this pipe, I just need it done so I could go on with the work. I paste here only the code that matters, i didn't paste the whole code.

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

the result (for now) should be output on the screen: test roger roger

however I cant get it done. I seem to miss some little detail.

If you write to pipe->writePipe[WRITE_END] you need to read from pipe->writePipe[READ_END] . It seems that you try to read from pipe->readPipe[READ_END] but this is another pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM