#include "shm.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <unistd.h> //fork() head file
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MYFIFO "/bin/my_fifo"
void read_pipe(int pipefd, unsigned char *ucbuf_pipe, int *len)
{
*len = read(pipefd, ucbuf_pipe, BUFSIZ);
}
void write_pipe(int pipefd, unsigned char *ucbuf_pipe, int len)
{
write( pipefd, ucbuf_pipe, len);
}
int main(int argc, char *argv[])
{
pid_t pid;
int ishmid;
int imsgidc;
int imsgidd;
int imsgsendnum = 0;
int imsgreceive = 0;
//st_shm * pshm = NULL;
st_msg stmsg;
st_msg stmsg_r;
stmsg_r.mtype = 1;
memset(stmsg_r.mtext,'\0', BUFSIZE);
unsigned char ucbuf[BUFSIZE] = {'\0'};
unsigned char ucbuf_pipe[BUFSIZE] = {'\0'};
unsigned char ucbuf_fifo[BUFSIZE] = {'\0'};
int len = 0;
int pipefd[2];
if( ishmid < 0 )
{
printf("shmget error\n");
exit(0);
}
else
{
imsgidd = msgget(MSGKEYD, 0666|IPC_CREAT);
imsgidc = msgget(MSGKEYC, 0666|IPC_CREAT);
if( (imsgidc < 0) || (imsgidd < 0) )
{
printf("c msgget fail\n");
}
while(1)
{
imsgsendnum = 0;
imsgreceive = 0;
#if 1
do
{
imsgreceive = msgrcv(imsgidc, &stmsg, BUFSIZ, 0, 0);
if( imsgreceive >= 0 )
{
//printf("imsgreceive is %d\n", imsgreceive);
stmsg.mtext[imsgreceive] = '\0';
printf("d rcv msg from C:%s\n", stmsg.mtext);
}
}while(imsgreceive == -1);
#endif
//memcpy(stmsg.mtext, stmsg.mtext, imsgreceive+1);
sprintf(stmsg_r.mtext, "hello C!\n");
imsgsendnum = msgsnd(imsgidd, &stmsg_r, strlen(stmsg_r.mtext), 0);
//printf("imsgsendnum is %d\n", imsgsendnum);
if( imsgsendnum >= 0 )
{
//printf("imsgsendnum is %d\n", imsgsendnum);
//break;
}
else
{
sleep(1);
}
if( pipe(pipefd) == -1 )
{
printf("pipe error\n");
}
pid = fork();
if( pid == 0 )//子进程 返回0
{//子进程
sleep(1);
close(pipefd[1]);
read_pipe(pipefd[0], ucbuf_pipe, &len);//读取无名管道数据
close(pipefd[0]);
printf("pipe read :%s\n", ucbuf_pipe);
if(access(MYFIFO, F_OK) != 0 )
{
int ret = mkfifo(MYFIFO, 0777);
if(ret != 0)
{
printf("Could not create fifo %s\n", MYFIFO);
exit(EXIT_FAILURE);
}
}
//write_fifo();//用有名管道传递数据给进程B
int pipe_fd = open(MYFIFO, O_RDWR);
int wlen = write(pipe_fd, ucbuf_pipe, len);
printf("wlen = %d\n", wlen);
int rlen = read(pipe_fd, ucbuf, len);
printf("rlen = %d\n", rlen);
ucbuf[rlen] = '\0';
printf("fifo read :%s\n", ucbuf);
close(pipe_fd);
sleep(2);
}
else
{//父进程
int len = 0;
close(pipefd[0]);
write_pipe(pipefd[1], stmsg.mtext, imsgreceive);//消息队列读回来的数据通过无名管道发出去
close(pipefd[1]);
sleep(1);
if(access(MYFIFO, F_OK) != 0 )
{
int ret = mkfifo(MYFIFO, 0777);
if(ret != 0)
{
printf("Could not create fifo %s\n", MYFIFO);
exit(EXIT_FAILURE);
}
}
//write_fifo();//用有名管道传递数据给进程B
int pipe_fd = open(MYFIFO, O_RDONLY);
memset(ucbuf_fifo, '\0', BUFSIZE);
len = read(pipe_fd, ucbuf_fifo, BUFSIZE);
printf("len = %d\n", len);
ucbuf_fifo[len] = '\0';
printf("fifo read :%s\n", ucbuf_fifo);
close(pipe_fd);
}
}
}
return 0;
}
评论0