当前位置: 动力学知识库 > 问答 > 编程问答 >

c - pipe : write to front of pipe

问题描述:

I came across TIMM_OSAL_WriteToFrontOfPipe and TIMM_OSAL_WriteToPipe in the link

In TIMM_OSAL_WriteToPipe looks like, data is simply written to write end of pipe.

where as,

In TIMM_OSAL_WriteToFrontOfPipe, data is written at the write end, then again read and again written.

I tried to reproduce the same using a sample program below. But could not understand the point of reading and writing again. Could someone please throw some light on it ?

int main(void)

{

int fd[2];

int status = pipe (fd);

if (status) {

fprintf(stderr, "** pipe create failed");

return 0;

}

status = fork();

if (status < 0)

fprintf (stderr, "** fork failure!");

if (status == 0){

//close (fd[1]);

char buf[5] = {0,};

int ret_size;

fprintf(stderr, "child going to sleep...\n");

sleep (10);

fprintf(stderr, "\nchild woken up...\n");

ret_size = read (fd[0], buf, 5);

fprintf (stderr, "child printing ...\n");

fprintf (stderr, "%s\n", buf);

} else {

char buf[5] = {0};

int read_sz;

int write_sz;

//close (fd[0]);

strcpy(buf,"1");

write_sz = write (fd[1], buf, 1);

strcpy(buf,"2");

write_sz = write (fd[1], buf, 1);

strcpy(buf,"3");

write_sz = write (fd[1], buf, 1);

strcpy(buf,"4");

write_sz = write (fd[1], buf, 1);

if (write_sz < 0)

fprintf (stderr, "write failed");

else

fprintf(stderr, "written 1234\n");

memset(buf, 0, sizeof(buf));

strcpy(buf,"5");

write(fd[1], buf, 1);

memset(buf, 0, sizeof(buf));

read_sz = read (fd[0], buf, 5);

if (read_sz > 0)

fprintf(stderr, "read data :\n%s\n", buf);

//write back to pipe

write (fd[1], buf, 5);

}

return 0;

}

Output:

written 1234

read data :

12345

child going to sleep...

child woken up...

child printing ...

12345

I also tried by not forking and reading and writing in the same process.

网友答案:

WriteToFrontOfPipe means:

|----------------CURRENT_DATA| -> |------CURRENT_DATA YOUR_DATA|

Because pipe acts like queue, it takes 3 operations:

|------YOUR_DATA CURRENT_DATA| // write your data

|-------------------YOUR_DATA| // read tail to put your data in front

|------CURRENT_DATA YOUR_DATA| // save previous data back

分享给朋友:
您可能感兴趣的文章:
随机阅读: