- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/stat.h>
- #include <sys/msg.h>
- #include <errno.h>
- #define BUFFER 255
- #define PERM S_IRUSR | S_IWUSR
- struct msgtype
- {
- long mtype;
- char buffer[BUFFER+1];
- };
- void recv(int msgid)
- {
- while(1)
- {
- int fd[2];
- pid_t pid;
- if(pipe(fd) < 0)
- {
- fprintf(stderr,"pipe error!\n");
- exit(-1);
- }
- if((pid = fork()) == 0)
- {
- close(fd[0]);
- int rc;
- struct msgtype msg;
- if((rc = msgrcv(msgid,&msg,sizeof(struct msgtype),0,0)) == -1)
- {
- fprintf(stderr,"msgrcv error!\n");
- exit(-1);
- }
- rc = write(fd[1],msg.buffer,strlen(msg.buffer));
- if(rc < 0)
- {
- fprintf(stderr,"write error!\n");
- exit(-1);
- }
- exit(0);
- }
- else if(pid > 0)
- {
- char buf[256] = {0};
- fd_set rfds;
- struct timeval tv;
- int rc;
- FD_ZERO(&rfds);
- FD_SET(fd[0],&rfds);
- tv.tv_sec = 3;
- tv.tv_usec = 0;
- rc = select(fd[0]+1,&rfds,NULL,NULL,&tv);
- if(-1 == rc)
- {
- fprintf(stderr,"select error!\n");
- exit(-1);
- }
- else if(rc)
- {
- if(FD_ISSET(fd[0],&rfds))
- {
- rc = read(fd[0],buf,256);
- buf[rc] = 0;
- if(rc == -1)
- {
- fprintf(stderr,"read error!\n");
- exit(-1);
- }
- printf("I have receive a message : %s\n",buf);
- }
- }
- else
- {
- printf("no data timeout!\n");
- return ;
- }
- }
- }
- }
- int main(int argc, char **argv)
- {
- if(argc != 2)
- {
- printf("usage ./test string\n");
- exit(-1);
- }
- int msgid = msgget(IPC_PRIVATE, PERM | IPC_CREAT | IPC_EXCL);
- if(msgid == -1)
- {
- fprintf(stderr,"msgget error!\n");
- exit(-1);
- }
- pid_t pid;
- int i;
- for(i = 0; i < 4; i++)
- {
- pid = fork();
- if(pid == 0 || pid == -1)
- break;
- }
- if(pid == 0)
- {
- struct msgtype msg;
- msg.mtype = 1;
- strcpy(msg.buffer,argv[1]);
- int rc = msgsnd(msgid,&msg,sizeof(struct msgtype),0);
- if(rc == -1)
- {
- fprintf(stderr,"msgsnd error!\n");
- exit(-1);
- }
- else
- {
- printf("msgsnd success!\n");
- }
- }
- else if(pid > 0)
- {
- pthread_t tid,tid2,tid3,tid4,tid5;
- pthread_create(&tid,NULL,(void*)recv,(void*)msgid);
- pthread_join(tid,NULL);
- wait(NULL);
- }
- else
- {
- fprintf(stderr,"fork error!\n");
- exit(-1);
- }
- return 0;
- }
复制代码 以上是我的代码,使用select与管道来实现消息队列超时退出。其中是在子进程中调用msgrcv函数,在这里可能会产生阻塞,现在有个问题,如果msgrcv阻塞了,父进程可以监控到超时,那么父进程中就退出了,那么子进程会不会退出呢?我不了解select是让谁退出了呢? |
|