【发布时间】: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。