gpt4 book ai didi

c - 为什么下面的C代码会跳过read()系统调用去执行下一个write()系统调用?

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:47 25 4
gpt4 key购买 nike

我的问题是关于 Linux 系统编程,特别是关于读写 API。

我正在编写一个复制 shell 的程序。它接受一个字符串参数并用空格分隔符对其进行标记。根据第一个 token 的命令,它使用其余 token 作为参数执行操作。到目前为止,我只为“添加”命令实现了这一点。代码循环运行,直到用户输入“n”表示“继续?” [是/否]'。但是,在第一次迭代之后,我的程序在第一次 write() 调用后跳过 read() 以输入命令,并以“继续?”结束。写()调用。为什么它在第一个 write() 之后立即跳过 read() 调用?

int main (int argc, char *argv[]) {
int true=0;
while (true==0) {
char buff1[]="Please enter your command\n";
int count1= strlen(buff1);
write (STDOUT_FILENO, buff1, count1);
char buff2[100];
int count2=read (STDIN_FILENO, buff2, 100);
buff2[count2-1]='\0';
char *list[30]; //This creates an array of character pointers (strings)
/*
* Begin tokenization and entering tokens in list
*/
const char delim[]=" ";
char *token;
token=strtok(buff2, delim);
const char newline[]="\n";
int i=0;
while (token!= NULL) {
write (STDOUT_FILENO, newline, strlen(newline));
list[i]=token;
write (STDOUT_FILENO, list[i], strlen(list[i]));
i++;
token=strtok(NULL,delim);
}
/*
* End tokenization
*/

/*
* Begin Addition operation
*/
const char add[]="add";
if (strcmp(list[0], add)==0) {
int result=0;
for (int j=1; j<i; j++) {
result+=atoi(list[j]);
}
char sum[50];
int sumcount=sprintf(sum, "%d", result);
write (STDOUT_FILENO, newline, strlen(newline));
write (STDOUT_FILENO, sum, sumcount);
}
/*
* End Addition operation
*/


char *truefalse;
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, truefalse, 1);
if (*truefalse=='n') {
true=1;
}

}
return 0;
}

As this output image shows, in the second iteration, after asking me to enter a command, the code skips to asking me to continue rather than actually reading my command

最佳答案

你的程序有未定义的行为。

你使用了一个没有被初始化的指针来指向任何有效的东西。

线

char *truefalse;

声明了一个指针,但它还没有被初始化以指向任何有效的东西。你继续在行中使用它

read (STDIN_FILENO, truefalse, 1);

代替

char *truefalse;
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, truefalse, 1);

使用

char truefalse; // Make it an object instead of a pointer.
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, &truefalse, 1); // Use the address of the variable.

更新

您的代码在第二次迭代中不等待您输入任何内容的原因是换行符仍留在输入流中。第二次调用只是读取换行符。

在阅读问题的答案后,您需要代码来跳过该行的其余部分。

最简单的方法是使用:

int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');

关于c - 为什么下面的C代码会跳过read()系统调用去执行下一个write()系统调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244903/

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