在此程序中,当我将strncmp函数与字符串“ end”一起使用时,使用信号量(在DEBIAN上)与信号量共享内存(Producer / Consumer),以便将0标志(正在运行)置为0以终止一段时间,strncmp不会t识别我插入外壳的单词end。谢谢。
这只是我要使用的第一个过程:
//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);
}
这是第二个过程:
生产者
#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);
}
最佳答案
我用调试方法解决了这个问题。在shmat参数中,我写了semID
而不是shmID
shmP=shmat(semID, (void *)0, 0)
谢谢大家。
[解决]
关于c - c-strncmp“结束”一段时间不会终止循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46101654/