c - 为什么当我按 CTRL+C 时程序读取零字节?(C-Posix)
问题描述
我的程序必须这样做:用户必须通过命令行为文件传递 N 个绝对路径名。然后第i个线程,0<=i<= N,必须在第i个文件中写入用户使用scanf(或fgets)传递的字符串。如果按下 CTRL+C,程序必须打印用户使用 scanf 传递的所有字符串。
当我运行它并为 N 个文件中的 1 个插入一个字符串并按 CTRL+C 时,在函数 onPress 中,函数 read 返回 0(我认为在这种情况下不表示文件指针位于文件末尾) 并且它只打印字符串“Strings:”
代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
pthread_mutex_t mutex;
int fdGlobal;
void* writer (int* arg) {
int fd_in = *(arg);
char buffer[100];
pthread_mutex_lock(&mutex);
printf("Write the string that you want to insert in the file\n");
scanf("%s", &buffer);
write(fd_in, &buffer, strlen(buffer));
write(fdGlobal, &buffer, strlen(buffer));
printf("Finished\n");
pthread_mutex_unlock(&mutex);
}
void onPress(int sig) {
char buff[100];
printf("I'm going to print all strings passed in files...\n");
int rd = read(fdGlobal, &buff, sizeof(buff));
if (rd == -1) perror("Error in the read of global file\n");
printf("I read %d bytes\n", rd);
printf("Strings: %s\n", buff);
exit(0);
}
void main (int argc, char* argv[]) {
int fds[argc-1];
pthread_t tid[argc-1];
int i, mu;
if (argc<=1) {
printf("Insert a number >=1 of pathname/s\n");
}
for ( i = 1 ; i<argc; i++) {
if (argv[i][0] != '/') {
printf("Insert a pathname\n");
}
}
signal(SIGINT, onPress);
fdGlobal = open("globalFile.txt", O_CREAT|O_RDWR, 0666);
if (fdGlobal == -1) perror("Error in the open of global file\n");
mu = pthread_mutex_init(&mutex, NULL);
if (mu < 0) perror("Error in the creation of mutex\n");
for (i=0; i<argc-1; i++) {
fds[i] = open(argv[i+1], O_CREAT|O_WRONLY, 0666);
if (fds[i] < 0 ) perror("Error in the open of the file\n");
pthread_create ( &tid[i], NULL, (void*) writer, &(fds[i]) );
}
for (i=0; i<argc-1; i++) {
pthread_join(tid[i], NULL);
}
}
解决方案
您的代码存在许多围绕异步信号安全、缓冲区大小和(非)并发性的问题,但到目前为止,您描述的症状最可能的原因是:
函数读取返回 0
是您认为文件指针不在文件末尾的信念是错误的。
实际上,read()
返回 0 是文件偏移量当前位于(或过去)文件末尾的积极指标。如果文件是新创建的,那么我看不出有任何理由认为偏移量会在其他任何地方。即使文件已经存在,您也需要将文件偏移量移回开头,以读取程序当前运行时写入的数据。例如,您可以通过适当的调用来做到这一点lseek()
。
推荐阅读
- powershell - 无法使用服务帐户创建 SSL/TLS 安全通道调用 webrequest 任务调度程序
- amazon-web-services - cloudformation 可以为我插入 route53 记录吗?
- java - 多继承接口中的同名默认方法。爪哇
- c++ - 为什么默认参数不能与参数包一起使用?
- html - IOS safari 和 Windows Firefox 之间的 CSS line-height 呈现不同
- python - 从 Py 脚本向 Ansible 传递变量
- javascript - javascript递归多维问题
- regex - Perl 正则表达式匹配字符串包含字母/数字/点
- java - 使用休眠以列表形式获取对象
- runtime-error - 在声明模块的 io 时出现意外错误:“尝试重新分配绑定到 chisel3.core.UInt@29a”