Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* touch queue; gcc -Wall -Wextra -pedantic -std=c99 -o a a.c && a */
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <sys/wait.h>
- #include <unistd.h>
- typedef struct Mymsg {
- long mtype; /* Message type */
- char mtext[20]; /* Message body */
- } Mymsg;
- int main() {
- key_t key = ftok("queue", 'x');
- int id = msgget(key, IPC_CREAT);
- if (id == -1) {
- printf("msgget error");
- exit(EXIT_FAILURE);
- }
- pid_t child_pid = fork();
- if (child_pid == -1) {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- if (child_pid == 0) {
- printf("CHILD PROCESS\n");
- Mymsg message;
- message.mtype = 1;
- strcpy(message.mtext, "test");
- if (msgsnd(id, &message, sizeof(message)-sizeof(long), 0) == -1) {
- perror("msgsnd");
- exit(EXIT_FAILURE);
- }
- exit(EXIT_SUCCESS);
- }
- else
- {
- int status;
- if (waitpid(child_pid, &status, 0) == -1) {
- perror("waitpid");
- exit(EXIT_FAILURE);
- }
- if (WIFSIGNALED(status)) {
- fprintf(stderr, "Child killed by signal %d\n", WTERMSIG(status));
- exit(EXIT_FAILURE);
- }
- if (!WEXITSTATUS(status)) {
- fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(status));
- exit(EXIT_FAILURE);
- }
- printf("PARENT PROCESS\n");
- Mymsg message;
- if (msgrcv(id, &message, sizeof(message)-sizeof(long), 1, 0) == -1) {
- perror("msgrcv");
- exit(EXIT_FAILURE);
- }
- printf("READ: %s\n", message.mtext);
- if (msgctl(id, IPC_RMID, 0) == -1) {
- perror("msgctl");
- exit(EXIT_FAILURE);
- }
- exit(EXIT_SUCCESS);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement