Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <errno.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- struct my_msgbuf {
- long mtype;
- char mtext[200];
- };
- int checkCLArgs(char *num1, char *num2) {
- int i;
- for(i = 0; num1[i] != '\0'; i++) {
- if(!isdigit(num1[i]))
- return 1;
- }
- for(i = 0; num2[i] != '\0'; i++) {
- if(!isdigit(num2[i]))
- return 1;
- }
- return 0;
- }
- void error(const char *errMsg) {
- fprintf(stderr, "%s\n", errMsg);
- exit(-1);
- }
- int main(int argc, char **argv) {
- if(argc != 3)
- error("Usage: ./main N M\nN - number of cannibal processes, M - number of missionary processes");
- if(checkCLArgs(argv[1], argv[2]))
- error("Please enter positive integers only!");
- int i;
- pid_t pid;
- struct my_msgbuf buf;
- int msqid;
- key_t key = (key_t) getuid();
- char text[]="Hello from boat!\n";
- int N = (int) strtol(argv[1], (char **)NULL, 10);
- int M = (int) strtol(argv[2], (char **)NULL, 10);
- if(N <= 0 || M <= 0)
- error("Value of N or M is not greater than 0");
- printf("N = %d, M = %d\n", N, M);
- int cannibalArr[N];
- int missionaryArr[M];
- for(i = 0; i < N; i++) {
- pid = fork();
- switch(pid) {
- case -1:
- error("Error while creating cannibal proccess!");
- case 0:
- execl("./person", "C", NULL);
- exit(1);
- default:
- continue;
- }
- }
- for(i = 0; i < M; i++) {
- pid = fork();
- switch(pid) {
- case -1:
- error("Error while creating missionary proccess!");
- case 0:
- execl("./person", "M", NULL);
- exit(1);
- default:
- continue;
- }
- }
- printf("Boat: created %d cannibals and %d missionaries\n", N, M);
- if ((msqid = msgget(key, 0600 | IPC_CREAT)) == -1) {
- error("msgget");
- }
- while(1) {
- sleep(2);
- if (msgsnd(msqid, (struct msgbuf *)&buf, strlen(text)+1, 0) == -1)
- error("msgsnd");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement