[英]Inter-Process Communication (IPC) using Pipes
假設您有兩個用於問答的變量,如下所示 char* questions[] = {"Quit", "In which university do you?", "which course you are learning?", "what is your area?" };
char* answers[] = {“退出”,“DAIICT”,“系統軟件”,“內核編程”};
• 父進程將接受用戶輸入的問題編號。 如果問題編號在 0 到 3 之間,則問題的實際文本將使用以下方式從父進程發送到子進程。
寫(fd1[寫],問題[que],strlen(問題[que])+1);
• 一旦父母將問題發送給孩子,它就會使用以下內容等待孩子回復。
bytesRead = 讀取(fd2[READ],消息,MSGLEN);
• 當子進程收到以下問題時。
bytesRead = read(fd1[READ], message, MSGLEN);
• 子進程然后查找它從 questions[] 字符串數組接收到的問題的索引。 它使用該索引從 answers[] 字符串數組中獲取正確答案。
• 子進程然后使用以下命令向父進程回復答案。
寫(fd2[寫],答案[que],strlen(答案[que])+1);
• 如果孩子發現問題編號等於0(即退出),則在關閉所有打開的文件句柄后退出。 父進程在從子進程中讀取等於 0 的問題號並在收到“退出”作為子進程的答案后關閉所有打開的文件句柄並使用 wait() 系統調用等待子進程退出,以確保我們不會創建僵屍子進程. 一旦 parent 退出 wait() 系統調用,它也會退出。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define READ 0
#define WRITE 1
int main()
{
int i,que,bytesRead;
int fd1[2],fd2[2];
char message[100];
char* questions[] = {"Quit","In which university do you study?","Which course are you studying?","What is your area of interest?"};
char* answers[] = {"Quit", "DAIICT", "Systems Software", "Kernel Programming"};
pipe(fd1);
pipe(fd2);
if(fork() ==0)
{
close(fd1[WRITE]);
close(fd2[READ]);
while(1){
bytesRead = read(fd1[READ], message,100 );
for(i=0;i<4;i++)
{
if(strcmp(message,questions[i])==0)
{`enter code here`
break;
}
}
write(fd2[WRITE], answers[i], strlen(answers[i])+1);
if(i==0)
{
close(fd1[1]);
close(fd2[0]);
printf("Child exiting for you entered 0\n");
exit(0);
}
}
}
else
{
close(fd1[READ]);
close(fd2[WRITE]);
while(1)
{
printf("Enter digit from 0 to 3\n");
scanf("%d", &que);//dont show correct output if input is greater than 3
printf("Your choice is '%s'\n",questions[que]);
write(fd1[WRITE], questions[que], strlen(questions[que])+1);
bytesRead = read(fd2[READ], message, 100);
if(strcmp(message,answers[0])==0)
{
close(fd1[WRITE]);
close(fd2[READ]);
wait(fork());
printf("Parent exiting for you entered 0\n");
exit(0);
}
printf("Answer is '%s' \n",message);
}
return 0;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.