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

问题描述 投票:-1回答:1

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

当我运行这个并且我为N个文件中的一个插入一个字符串并按CTRL + C时,在onPress函数中,函数read返回0(我认为在这种情况下不表示文件指针位于文件末尾)它只打印字符串“字符串:”

码:

#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);
  }
  }
c multithreading posix eof
1个回答
3
投票

您的代码存在许多围绕异步信号安全性,缓冲区大小和(非)并发性的问题,但到目前为止,您描述的症状的最可能原因是:

函数read返回0

你认为文件指针不在文件末尾的信念是错误的。

实际上,返回0的read()是文件偏移当前处于(或过去)文件末尾的正指示。如果文件是新创建的,那么我认为没有任何理由认为偏移量会在其他任何地方。即使文件已经存在,您也需要将文件偏移量移回到开头,以读取当前运行程序中写入的数据。例如,您可以通过适当调用lseek()来完成此操作。

© www.soinside.com 2019 - 2024. All rights reserved.