Question
Create two C++ programs.
Have the first read a single argument that is the string representation of an integer. Loop that many times and display "Process: PID #" where PID is the process identifier and # is 1 -- n (n from the first argument). Also have this program return n as its status.
Have the second create a child process and the execute the first program, passing a argument of 5. Have this program wait for the child process exit and report its status.
Your output should look approximately like:
The most relevant manual pages include sleep(3), execl(3), wait(2), perror(3), fork(2), exit(3).
Explanation / Answer
#include #include #include #include #include #define MSGSZ 128 /* * Declare the message structure. */ typedef struct msgbuf { long mtype; char mtext[MSGSZ]; } message_buf; main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; message_buf sbuf; size_t buf_length; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ key = 1234; (void) fprintf(stderr, " msgget: Calling msgget(%#lx, %#o) ", key, msgflg); if ((msqid = msgget(key, msgflg )) < 0) { perror("msgget"); exit(1); } else (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d ", msqid); /* * We'll send message type 1 */ sbuf.mtype = 1; (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d ", msqid); (void) strcpy(sbuf.mtext, "Did you get this?"); (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d ", msqid); buf_length = strlen(sbuf.mtext) + 1 ; /* * Send a message. */ if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { printf ("%d, %d, %s, %d ", msqid, sbuf.mtype, sbuf.mtext, buf_length); perror("msgsnd"); exit(1); } else printf("Message: "%s" Sent ", sbuf.mtext); exit(0); } #include #include #include #include #define MSGSZ 128 /* * Declare the message structure. */ typedef struct msgbuf { long mtype; char mtext[MSGSZ]; } message_buf; main() { int msqid; key_t key; message_buf rbuf; /* * Get the message queue id for the * "name" 1234, which was created by * the server. */ key = 1234; if ((msqid = msgget(key, 0666)) < 0) { perror("msgget"); exit(1); } /* * Receive an answer of message type 1. */ if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) { perror("msgrcv"); exit(1); } /* * Print the answer. */ printf("%s ", rbuf.mtext); exit(0); }