繁体   English   中英

为什么当我按CTRL + C时程序读取零字节? (C-Posix)

[英]Why when I press CTRL+C the program reads zero bytes? (C-Posix)

我的程序必须这样做:用户必须通过命令行为文件传递N个绝对路径名。 然后,第i个线程(0 <= i <= N)必须在第i个文件中写入用户通过scanf(或fgets)传递的字符串。 如果按下CTRL + C,则程序必须打印用户通过scanf传递的所有字符串。

当我运行此命令并为N个文件中的1个插入字符串并按CTRL + C时,在函数onPress中,函数读取返回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()来完成此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM