avd*_*avd 1 c unix pipe synchronize
假设父和子都使用一个管道进行写入和读取意味着当一个写入时只有其他读取,否则它会阻塞.有什么办法吗?我尝试使用睡眠功能,但由于竞争条件,它没有给出正确的输出.这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGSIZE 16
main ()
{
int i;
char *msg = "How are you?";
char inbuff[MSGSIZE];
int p[2];
pid_t ret;
pipe (p);
ret = fork ();
if (ret > 0)
{
i = 0;
while (i < 10)
{
write (p[1], msg, MSGSIZE);
sleep (2);
read (p[0], inbuff, MSGSIZE);
printf ("Parent: %s\n", inbuff);
i++;
}
exit(1);
}
else
{
i = 0;
while (i < 10)
{
sleep (1);
read (p[0], inbuff, MSGSIZE);
printf ("Child: %s\n", inbuff);
write (p[1], "i am fine", strlen ("i am fine"));
i++;
}
}
exit (0);
}
Run Code Online (Sandbox Code Playgroud)
您无法在单个管道上执行双向同步.
您可以在Unix域套接字上进行双向同步.
| 归档时间: |
|
| 查看次数: |
1593 次 |
| 最近记录: |