gpt4 book ai didi

c- strncmp "end"一段时间不会终止循环

转载 作者:行者123 更新时间:2023-11-30 19:33:17 31 4
gpt4 key购买 nike

在这个关于带有信号量的共享内存(生产者/消费者)的程序中(在 DEBIAN 上),当我使用带有字符串“end”的 strncmp 函数时,为了打开 0 标志(运行)来终止 while 循环, strncmp 无法识别我插入到 shell 中的单词结尾。谢谢。

这只是我想使用的第一个进程:

//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);
}

最佳答案

我用debug方法解决了这个问题。在 shmat 参数中,我写了 semID 而不是 shmID shmP=shmat(semID, (void *)0, 0)

谢谢大家。

[已解决]

关于c- strncmp "end"一段时间不会终止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101654/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com