【问题标题】:Endless request for input when calling open()调用 open() 时无休止的输入请求
【发布时间】:2021-11-13 13:25:25
【问题描述】:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <string.h>

int main(){
    int fd;
    size_t size;
    char name[]="aaa.fifо";
    umask(0) ;
    if (mknod(name, S_IFIFO | 0666, 0) < 0){  
        printf("Can\'t create FIFO\n");
        _exit(-1);
    }
    if ((fd = open(name, O_WRONLY)) < 0){ 
        printf("Can\'t open FIFO for writing\n");
        _exit(-1);
    }
    char message[60];
    while(true){
        message[0] = 0;
        std::cin.clear();
        std::cin >> message;
        if(!strcmp(message,"exit"))
        {
            printf("Exit to programm\n");
            break;
        }
        size = write(fd, message, 60);
        if (size < strlen(message)) {
            printf("Can\'t write all string to FIFO\n");
            _exit(-1);
        }
    }
    close(fd);
    
    return 0;
}

通过打字,我意识到调用open()时出现了问题。

当我删除循环时,同样的问题即使 cout 在 main write 的开头没有任何作用,但是当你从 open() 中删除行时,一切正常

【问题讨论】:

  • 不要写 60 个字符。为空终止符写入您从用户 + 1 读取的尽可能多的字符。您还可以使用std::string 来读取用户输入。 std::string message; while(std::getline(std::cin, message)) { write(fd, message.c_str(), message.size() + 1); }
  • 除了std::cin 之外,还有什么东西可以让这个程序变成 C++ 吗?绝大多数是普通的旧 C。

标签: c++ linux


【解决方案1】:

我意识到调用open()时出现问题。

某些进程必须打开 FIFO 进行读取,然后您的 open() 继续。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 2016-09-26
    • 2017-11-05
    • 2020-04-27
    • 2022-07-06
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多