我遇到以下代码时出现问题:
struct {
int a, b;
sem_t client;
sem_t server;
} *shm_acc;
void server() {
while(1) {
sem_wait(&shm_acc->server);
if(shm_acc->a == -1 && shm_acc->b == -1)
return;
printf("The product of the two entered numbers is %d\n", shm_acc->a * shm_acc->b)
sem_post(&shm_acc->client);
}
}
void client() {
while(1) {
printf("Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.\n");
if(2 != scanf("%d %d\n", &shm_acc->a, &shm_acc->b) {
perror("An error occured. Please try again\n");
while(getchar() != '\n');
continue;
}
sem_post(&shm_acc->server);
if(shm_acc->a == -1 && shm_acc->b == -1)
return;
sem_wait(&shm_acc->client);
}
exit(EXIT_SUCCES);
}
int main() {
setbuf(stdout, NULL);
int shm = 0;
shm = shmget(IPC_PRIVATE, SHAREDMEM_SIZE, S_IRUSR | S_IWUSR);
if(shm == -1)
perror("Failed to create shared memory.\n");
shm_acc = shmat(shm, NULL, 0);
sem_init(&shm_acc->client, 1, 0);
sem_init(&shm_acc->server, 1, 0);
pid_t pid = fork();
if(pid == 0) {
client();
shmdt(shm_acc);
} else if(pid >0) {
server();
waitpid(pid, NULL, 0);
sem_destroy(&shm_acc->server);
sem_destroy(&shm_acc->client);
} else if(pid == -1) {
perror("fork");
sem_destroy(&shm_acc->server);
sem_destroy(&shm_acc->client);
}
return 0;
}
在上面的代码中,客户端和服务器使用POSIX共享内存相互通信。父进程表示服务器,子进程表示客户端。另外,我正在使用POSIX信号量。该 服务器必须等到客户端在处理输入之前输入两个值, 客户端必须等到服务器完成处理输入并在提示输入新值之前打印输出
问题是,代码的行为不应该如此。
应该是什么:
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
2 2
The product of the two entered values is 4.
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
3 3
The product of the two entered values is 9.
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
-1 -1
//exit
但它的作用是:
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
2 2 // after entering it doesn't calculate the input
2 3 // after entering again it calculates 2x2
The product of the two entered values is 4.
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
3 3
The product of the two entered values is 6. // This is the result of input 2x3, see above
Please enter two unsigned integer with whitespace in between. For exit enter -1 -1.
-1 -1
The product of the two entered values is 9
2 4
// Now it terminates.
我不知道出了什么问题。有谁知道,代码为什么这样做?
答案 0 :(得分:3)
将\n
留在scanf
格式字符串的末尾几乎总是一个问题(fscanf
不是问题,因为它不是交互式的),因为任何空白字符在格式字符串中真正代表“0或更多(可能无限多)空白字符” - 它们可以是任何空格字符(空格,制表符或回车符)。
因此,当您将\n
(或<space>
或\t
)放在格式字符串的末尾时,scanf
将不会停止并返回输入,直到它看到非空白字符(或遇到某种匹配错误)。从您的角度来看,它看起来似乎不是打印提示或处理输入;那是因为它不是 - 它仍然在同一个地方。如果您只在行上键入一个数字也会发生同样的事情 - 程序会暂停,因为scanf
仍然在等待您输入第二个数字(如前所述,您输入的输入键“适合”格式中的空格,因此还没有匹配的错误。)
由于%d
(以及除%c
和%[
以外的每个格式说明符)都忽略了 的前导空格,因此您经常会发现包括它们是没有必要的。