#include #include #include #include #include struct { pthread_mutex_t mtx; char text[256]; } item[5]; const char *arg0; void *threadFunc(intptr_t num) { char name[1024], cmd[1024]; sprintf(name, "%s.pipe.%ld", arg0, num); sprintf(cmd, "rm -f %s; mkfifo %s", name, name); system(cmd); FILE *myPipe = fopen(name, "r+"); while (1) { char line[1024], nl; fscanf(myPipe, "%1023[^\n]%c", line, &nl); int argOne = atoi(line); if (argOne >= 5 || argOne < 0) continue; char *argTwoTxt = strchr(line, ' '); if (!argTwoTxt) { pthread_mutex_lock(&item[argOne].mtx); printf("T%ld reads %d as: %s\n", num, argOne, item[argOne].text); pthread_mutex_unlock(&item[argOne].mtx); continue; } argTwoTxt++; char *e; int argTwo = strtol(argTwoTxt, &e, 10); if (!*e && argTwo < 5 && argTwo >= 0 && argOne != argTwo) { pthread_mutex_lock(&item[argOne].mtx); pthread_mutex_lock(&item[argTwo].mtx); printf("T%ld copies %d to %d\n", num, argTwo, argOne); memcpy(item[argOne].text, item[argTwo].text, sizeof(item[argOne].text)); pthread_mutex_unlock(&item[argTwo].mtx); pthread_mutex_unlock(&item[argOne].mtx); } else { pthread_mutex_lock(&item[argOne].mtx); printf("T%ld assigns to %d the value: %s\n", num, argOne, argTwoTxt); memset(item[argOne].text, 0, sizeof(item[argOne].text)); strncpy(item[argOne].text, argTwoTxt, sizeof(item[argOne].text) - 1); pthread_mutex_unlock(&item[argOne].mtx); } } } int main(int argc, char **argv) { arg0 = argv[0]; printf("To use this program, write to one of the %s.pipe. the " "following:\n" " prints from item \n" " puts to item \n" " copies to item the text from item \n" "Valid pipe numbers are 0-4, valid item numbers are 0-4.", arg0); for (int i = 0; i < 5; ++i) pthread_mutex_init(&item[i].mtx, NULL); for (intptr_t i = 1; i < 5; ++i) { pthread_t tid; pthread_create(&tid, NULL, (void *(*)(void *))threadFunc, (void *)i); pthread_detach(tid); } threadFunc(0); }