c- strncmp "end" of a while doesn't kill the cycle

79 views Asked by At

in this program about shared memory(Producer/Consumer) with semaphores(on DEBIAN) when I use the strncmp function with the string "end", in order to turn on 0 a flag(running) to kill a while cycle,strncmp doesn't recognize the word end that I insert into the shell. Thank you.

This is only the first process that I want to use:

//CONSUMER
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "semafori.h" //semaphores SYSTEM V functions
#include <sys/shm.h>
#include <string.h>

#define SHM_KEY (key_t)1234
#define SEM_KEY (key_t)5678

#define WRITE_SEM 0
#define READ_SEM 1

#define TEXT_SIZE 2048

struct SharedData{
unsigned int count;
char text[TEXT_SIZE];
};


int main(void)
{

    int running=1;
    void *shmP;
    struct SharedData * p;
    int shmID;
    int semID;

    semID=semget(SEM_KEY,2,IPC_CREAT|0666);

    SEM_SET(semID, WRITE_SEM,1);
    SEM_SET(semID, READ_SEM, 0);

shmID=shmget(SHM_KEY, sizeof(struct SharedData), IPC_CREAT|0666);

shmP=shmat(semID, (void *)0, 0);
printf("Memoria agganciata all'indirizzo: %X\n", (int)shmP);

p=(struct SharedData *)shmP;

while(running!=0){
if(SEM_P(semID, READ_SEM)==-1) exit(EXIT_FAILURE);
if (strncmp(p->text, "end", 3) == 0) {
    running = 0;
}
else {
printf("Numero scambi effettuato: %u\nHai scritto: %s\n", p->count, p->text);
}
if(SEM_V(semID, WRITE_SEM)==-1) exit(EXIT_FAILURE);
}
if(shmdt(shmP)==-1){
fprintf(stderr, "shmdetach failed\n");
exit(EXIT_FAILURE);
}
if(shmctl(shmID, IPC_RMID, 0)==-1){
fprintf(stderr, "shmctl RMID failed\n");
exit(EXIT_FAILURE);
}
SEM_DEL(semID, 0);

exit(EXIT_SUCCESS);
}

This is the second process: PRODUCER

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include "semafori.h"

#define SHM_KEY (key_t)1234
#define SEM_KEY (key_t)5678
#define WRITE_SEM 0
#define READ_SEM 1
#define TEXT_SIZE 2048


struct SharedData{
unsigned int count;
char text[TEXT_SIZE];
};

int main(void)
{

    int running=1;
unsigned int count=0;
void *shmP;
struct SharedData *p;
int shmID, semID;
char buffer[TEXT_SIZE];

semID=semget(SEM_KEY, 2, IPC_CREAT|066);
shmID=shmget(SHM_KEY, sizeof(struct SharedData),IPC_CREAT|0666);

shmP=shmat(shmID, (void *)0, 0);

p=(struct SharedData*)shmP;

while(running!=0)
{
count++;
if(SEM_P(semID, WRITE_SEM)==-1) exit(EXIT_FAILURE);
printf("Inserisci testo: ");
fgets(buffer, BUFSIZ, stdin);
strncpy(p->text, buffer, TEXT_SIZE);
p->count=count;
if (strncmp(buffer, "end", 3) == 0) {
   running = 0;
}


if(SEM_V(semID, READ_SEM)==-1) exit(EXIT_FAILURE);
}

if(shmdt(shmP)==-1){
fprintf(stderr, "shmdt failure\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
1

There are 1 answers

0
amcnvbfgh On

I resolved the problem with debug method. In the shmat argument i wrote semID instead of shmID shmP=shmat(semID, (void *)0, 0)

Thank you everybody.

[RESOLVED]