【发布时间】:2018-05-26 09:54:50
【问题描述】:
您已经编写了一个代码,以便父母通过管道发送消息,孩子接收它并将其打印到屏幕上......然后孩子应该回复一个并且父母在管道内打印味精......代码与父子之间的通信完美配合..但是当涉及到相反的 close() 返回错误并且消息未传递时...请注意,我还使用共享内存来进行一些同步和控制..我知道孩子和父母之间有一种特殊类型的管道..但是如果它适用于该目的,我想使用一般情况,请告诉我这是不是真的..这是代码
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <errno.h>
#include <sched.h>
#include <string.h>
int main()
{
////creating shared memory with check///
int shmid ;
int err;
char *shm;
shmid = shmget(IPC_PRIVATE,3 ,IPC_CREAT | IPC_EXCL | 0666 );
shm=shmat(shmid,0, IPC_CREAT | IPC_EXCL | 0666 );
if (shmid > -1)
{
printf("shared memory created succefully\n");
shm[0]='C';
shm[1]='C';
shm[2]='C';
}
else
{
return 0;
}
/////////////////////////////////////////
//////////making pipe with check/////////
int testpipe[2];
int size_ptr ;
char buff1[51];
char buff2[51];
char buff3[51];
char buff4[51];
int check;
check = pipe(testpipe);
if (check > -1)
{
printf("pipe created succefully\n");
}
else
{
return 0 ;
}
////////////////////////////////////////
///////////making new process///////////
pid_t pid ;
pid = fork();
////////////////////////////////////////
///////////Executing process ///////////
if (pid > 0) //am in parent
{
//////////partA////////////////////
strcpy(buff1,"Hi am tweeting now ..\n");
// err = close(testpipe[0]);
printf("... Close state %d \n",err);
write(testpipe[1],buff1,25);
close(testpipe[1]);
printf("partA Ended ... Close state %d \n");
/////////////////////////////////////
shm[0] = 'O'; // lock 2 is opened here
shm[1] = 'C'; // lock 1 is closed
while(shm[1] != 'O');
/////////////////////////////////////
//////////partD///////////////////
//close(testpipe[1]);
err = read(testpipe[0],buff4,25);
//close(testpipe[1]);
printf(" error state%i \n",err);
printf("the output is : %s\n",buff4);
printf("part D Ended ...\n");
printf("Close state %d ... %i \n",err,EACCES);
shmdt(shm);
return 0;
}
else if (pid ==0) // am in child now
{
while(shm[0]!= 'O'); //from child read'
///////////////////////////////////
//////////partb////////////////////
read(testpipe[0],buff2,25);
//err = close(testpipe[0]);
printf("Close state %d \n",err);
printf("the output is : %s\n",buff2);
printf("partB Ended ... Close state %d\n",err);
//close(testpipe[0]);
//////////////////////////////////
/////////////// /part c////////////
close(testpipe[0]);
err = write(testpipe[1],buff3,25);
printf("III... Close state %d \n",err);
err = close(testpipe[1]);
printf("Close state %d \n",err);
printf("partC Ended ..\n");
shm[1] ='O';
/////////////////////////////////////////////////
//shm[1] = 'O';
shm[0] = 'C';
while(shm[0]!= 'O');
printf("process child closed\n");
}
else{
printf("Error Ocuured");
}
//////////////////////////////////////////
}
【问题讨论】:
-
管道是单向的。如果父母和孩子都在一个管道上读写,它会变得混乱。使用两个管道。确保你关闭了足够多的文件描述符。
-
我正在尝试采用两个管道方法......如果这不起作用,我会在这里发布......感谢您的快速评论:)