linux訊息序列(處理序間通訊)

來源:互聯網
上載者:User


linux訊息序列(處理序間通訊) [cpp] #include <stdlib.h>  #include <stdio.h>  #include <string.h>  #include <errno.h>  #include <unistd.h>  #include <sys/types.h>  #include <sys/ipc.h>  #include <sys/msg.h>      www.2cto.com  //需要自己定義的訊息佇列結構  struct msgStuct  {    long int msgType;    char strMsg[1024];  };    int  main ()  {    struct msgStuct msg_data;    int msgid;    char buffer[1024];    //建立一個訊息佇列    if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)      {    www.2cto.com        perror ("msgget failed with error: %d\n");        exit (EXIT_FAILURE);      }    while (1)      {        printf ("Send message: ");        fgets (buffer, 1024, stdin);      //初始化訊息類型        msg_data.msgType = 1;        strcpy (msg_data.strMsg, buffer);      //發送訊息        if (msgsnd (msgid, (void *) &msg_data, 1024, 0) == -1)      {        fprintf (stderr, "msgsnd failed\n");        exit (EXIT_FAILURE);      }        if (strncmp (buffer, "end", 3) == 0)      {        break;      }      }    exit (EXIT_SUCCESS);  }    www.2cto.com   [cpp] #include <stdlib.h>  #include <stdio.h>  #include <string.h>  #include <errno.h>  #include <unistd.h>  #include <sys/types.h>  #include <sys/ipc.h>  #include <sys/msg.h>    //需要自己定義的訊息佇列結構  struct msgStuct  {    long int msgType;    char strMsg[1024];  };    int  main ()  {    www.2cto.com    int msgid;    struct msgStuct msg_data;    //接收訊息優先順序    long int msgPriority = 0;//從隊列中取第一個    //建立一個訊息佇列  
   if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)//類似open()建立一個檔案返回它的檔案描述符,這裡是訊息序列      {        perror ("msgget failed with error");        exit (EXIT_FAILURE);      }    while (1)      {      //接收訊息        if (msgrcv (msgid, (void *) &msg_data, 1024,            msgPriority, 0) == -1)      {        perror ("msgrcv failed with error");        exit (EXIT_FAILURE);      }        printf ("Received message: %s", msg_data.strMsg);        if (strncmp (msg_data.strMsg, "end", 3) == 0)      {    www.2cto.com        break;      }      }    //刪除訊息佇列    if (msgctl (msgid, IPC_RMID, 0) == -1)      {        fprintf (stderr, "delete messagequeue error\n");        exit (EXIT_FAILURE);      }    exit (EXIT_SUCCESS);  }   第一個是send.c,第二個是recieve.c

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.