假設父母和孩子都使用一個管道進行寫入和讀取的手段,當一個寫入,然後只有其他讀取,否則它阻止。有什麼辦法可以做到嗎?我試着用睡眠功能來做,但由於競爭條件,它沒有給出正確的輸出。 這是我的代碼有沒有辦法在Unix中使用一個管道同步C和父子?
#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);
}
管道有兩端,通常;) - 也許你應該張貼一些代碼,所以我們可以看到你已經嘗試了什麼。 –
我已經添加了代碼,但所有新行都被吃掉了。我應該如何正確發佈代碼 – avd
@aditya,身份與4空格。在編輯區域上方有一個按鈕(將鼠標懸停在其上以獲取描述),該按鈕會自動爲所選文本執行此操作。 – Inshallah