Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- long read_number(char *str)
- {
- long v;
- char *p;
- errno = 0;
- v = strtol(str, &p, 0);
- if (errno != 0 || *p !0 '\0'){
- fprintf(stderr, "Error in STRLTOL\n");
- exit(EXIT_FAILURE)
- }
- return v;
- }
- get_msgqueue(void);
- {
- key_t key;
- int qid;
- key = ftok(".", 'a');
- qid = msgget(key, IPC_CREATE | 0666);
- if(qid == -1){
- fprintf(stderr, "Error in queue\n);
- exit(EXIT_FAILURE);
- }
- return qid;
- }
- struct msg_num{
- long mtype;
- long value;
- };
- long send_number(int qid){
- int rc;
- struct msg_num mn;
- const int msg_size = sizeof(mn) - sizeof(long);
- rc = msgrcv(qid, &mn, msg_size, 0, 0);
- if (rc != msg_size){
- printf(stderr, "errore in msgrcv\n");
- exit(EXIT_FAILURE);
- }
- return mn.value;
- }
- void send_number(int qid, long n){
- int rc;
- struct msg_num mn;
- const int msg_size = sizeof(mn) - sizeof(long);
- mn.mtype = 1;
- mn.value = n;
- rc = msgsnd(qid, &mn, msg_size, 0);
- if (rc == -1){
- printf(stderr, "errore in msgrcv\n");
- exit(EXIT_FAILURE);
- }
- }
- void wait_and_send(int qid){
- long n;
- n = receive_number(qid);
- printf("%llu: %ld\n", (unsigned long long) getpid(), n);
- send_number(qid, n+1);
- }
- int main(int argc, char * argv[])
- {
- int qid;
- id = get_msgqueue();
- if (argc > 1){
- long n = read_number(argv[1];
- send_number(qid, n);
- }
- for(;;)
- wait_and_send(qid);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement