Advertisement
gincum

Untitled

Feb 8th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <sys/types.h>
  6. #include <sys/ipc.h>
  7. #include <sys/msg.h>
  8.  
  9.  
  10.  
  11. long read_number(char *str)
  12. {
  13.     long v;
  14.     char *p;
  15.    
  16.     errno = 0;
  17.    
  18.     v = strtol(str, &p, 0);
  19.     if (errno != 0 || *p !0 '\0'){
  20.         fprintf(stderr, "Error in STRLTOL\n");
  21.         exit(EXIT_FAILURE)
  22.     }
  23.    
  24.     return v;
  25. }
  26.  
  27. get_msgqueue(void);
  28. {
  29.     key_t key;
  30.     int qid;
  31.     key = ftok(".", 'a');
  32.     qid = msgget(key, IPC_CREATE | 0666);
  33.     if(qid == -1){
  34.        fprintf(stderr, "Error in queue\n);
  35.       exit(EXIT_FAILURE);
  36.    }
  37.    return qid;
  38.    
  39. }
  40.  
  41.               struct msg_num{
  42.               long mtype;
  43.               long value;
  44.               };
  45.              
  46. long send_number(int qid){
  47.    int rc;
  48. struct msg_num mn;
  49.    const int msg_size = sizeof(mn) - sizeof(long);
  50.    rc = msgrcv(qid, &mn, msg_size, 0, 0);
  51.    if (rc != msg_size){
  52.        printf(stderr, "errore in msgrcv\n");
  53.        exit(EXIT_FAILURE);
  54.    }
  55.    return mn.value;
  56.        
  57. }
  58.  
  59. void send_number(int qid, long n){
  60. int rc;
  61. struct msg_num mn;
  62. const int msg_size = sizeof(mn) - sizeof(long);
  63.    
  64.    mn.mtype = 1;
  65.    mn.value = n;
  66.    rc = msgsnd(qid, &mn, msg_size, 0);
  67.    if (rc == -1){
  68.        printf(stderr, "errore in msgrcv\n");
  69.        exit(EXIT_FAILURE);
  70.    }        
  71.              
  72. }
  73.  
  74.              
  75. void wait_and_send(int qid){
  76.    long n;
  77.    n = receive_number(qid);
  78.    printf("%llu: %ld\n", (unsigned long long) getpid(), n);
  79.    send_number(qid, n+1);
  80. }
  81.  
  82.              
  83. int main(int argc, char * argv[])
  84. {
  85.   int qid;
  86.   id = get_msgqueue();
  87.        
  88.        if (argc > 1){
  89.            long n = read_number(argv[1];
  90.            send_number(qid, n);
  91.            }
  92.    for(;;)
  93.    wait_and_send(qid);
  94.                
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement