进程间通信

        //实现进程间相互通信  system V 消息队列实现
        #include <stdio.h>
        #include <stdlib.h>
        #include <unistd.h>
        #include <sys/types.h>
        #include <sys/ipc.h>
        #include <sys/msg.h>
        #include <string.h>
        #define MAX_TEXT 20
        struct msgbuf {
            long mtype; 
            char mtext[MAX_TEXT ]; 
        };  //传输数据的结构体
        int main(int argc,char *argv[])
        {
            pid_t pid;
        
            size_t len;
            int type;
            struct msgbuf snd;
            struct msgbuf rcv;
            char buf[MAX_TEXT];
            key_t key;
            int mid,ret;
    
            key = ftok(".", 'a');
        
            if((mid = msgget(key, IPC_CREAT|0770)) == -1) {
                perror("message queue create error");
                exit(1);
            }
            printf("%d\n", mid);
            system("ipcs -q");
            printf("-----------end with type 4 and data exit--MAX_TEXT 10----------\n");
            while(1) {
               
                fputs("输入你要传送的数据类型:", stdout);
                setbuf(stdin, NULL);
                scanf("%d", &type);
                snd.mtype = type;
                fputs("输入要传送的字符数据:", stdout);
                //清空键盘缓冲区,在linux下getchar(),fflush(stdin),rewind(stdin)都不起作用
                setbuf(stdin, NULL);
                fgets(buf, MAX_TEXT, stdin);
                memcpy(snd.mtext, buf, MAX_TEXT);
                ret = msgsnd(mid, (void *)&snd, MAX_TEXT, 0);
                if(ret == -1) {
                    exit(3);
                    perror("msgsnd error");
                }
                if(strncmp(snd.mtext, "exit", 4) == 0) {
                    break;
                }
            }
            system("ipcs -q");
            pid=fork();
            if(pid==0){
                while(1) {
                ret = msgrcv(mid, (void *)&rcv, MAX_TEXT, 0, 0);
                if(strncmp(rcv.mtext, "exit", 4) == 0) {
                    printf("type: %ld    data: %s", rcv.mtype, rcv.mtext);
                    break;
                }
                if(ret == -1) {
                    exit(3);
                    perror("msgrcv error");
                }
                printf("type: %ld    data: %s", rcv.mtype, rcv.mtext);
                }
            }
            else{
                wait(NULL);
                system("ipcs -q");
                msgctl(mid, IPC_RMID, (struct msqid_ds *)0);
                system("ipcs -q");
                exit(0);
            }
        
        }

标签: none

仅有一条评论

  1. Acquisto Finasteride Propecia Discount For Effexor Xr Order Zithromax Azithromycin cheapest cialis 20mg Comprar Viagra Generico En Espana Levitra Usa Oestrogel Mg

添加新评论