c - 在 C 中使用 read() 从 stdin 读取

标签 c stdin system-calls

我想从标准输入字符中读取字符并仅使用系统调用将其与不同的字符进行比较,我的问题是,给定代码:

#include "util.h"
#define STDOUT 1
#define STDIN 1
#define SYS_READ 3
#define SYS_WRITE 4
#define SYS_OPEN 5
#define SYS_CLOSE 6
#define SYS_LSEEK 19

int main (int argc , char* argv[], char* envp[])
{   
    char  str[512];
    int fd;
    if((fd= system_call(SYS_OPEN,STDIN,0, 0777))==-1){
        system_call(SYS_WRITE,STDOUT,"stdin error", 11);
    }

    while((system_call(SYS_READ,fd, str,1))>0){
        if((strncmp(";",str,1))==0){
            system_call(SYS_WRITE,STDOUT,str, 1);
            system_call(SYS_WRITE,STDOUT,"\n", 2);
        }
    else{
        system_call(SYS_WRITE,STDOUT,str, 1);       
        }
    }

return 0;
}

我有一个汇编文件可以将其转换为:“system_call(SYS_WRITE,STDOUT,”\n”, 2);”来写(...);
现在的问题是,我不知道如何让它等待输入,所以它永远不会启动 while 循环,因为它一开始就没有从输入中读取任何内容。


编辑系统调用的代码:

system_call:
push    ebp             ; Save caller state
mov     ebp, esp
sub     esp, 4          ; Leave space for local var on stack
pushad                  ; Save some more caller state

mov     eax, [ebp+8]    ; Copy function args to registers: leftmost...        
mov     ebx, [ebp+12]   ; Next argument...
mov     ecx, [ebp+16]   ; Next argument...
mov     edx, [ebp+20]   ; Next argument...
int     0x80            ; Transfer control to operating system
mov     [ebp-4], eax    ; Save returned value...
popad                   ; Restore caller state (registers)
mov     eax, [ebp-4]    ; place returned value where caller can see it
add     esp, 4          ; Restore caller state
pop     ebp             ; Restore caller state
ret                     ; Back to caller

已解决

我最终用 STDIN 解决了​​问题(define 关闭),并且没有定义 fd 来接收值,它最终工作了,不知道为什么仍然如此,我猜测 fd 被设置为非阻塞。

最佳答案

您将 STDIN 定义为 1,而它应该是 0。1 是 STDOUT,因此您尝试从仅用于写入的文件句柄中读取。

关于c - 在 C 中使用 read() 从 stdin 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22684634/

相关文章:

c - 系统调用如何转换为CPU指令?

c - 为什么终端 session 结束时所有进程都被杀死?

c - 线性搜索代码显示我的项目不存在。请帮我更正

c++ - 最佳 Base-10 仅 itoa() 函数?

character - perl6 如何重新打开 $*IN 进行输入?

c - 如何对音频 CD 驱动器使用 ioctl() 函数

c - 从txt文件C中读取整数

c++ - LNK2001 : unresolved external symbol "void __cdecl func1(struct Stru1 *)"

python - 在子进程中使用标准输入

在 C 中检查 exec 是否正在写入 stdin