【问题标题】:Permission denied when trying to write into log file尝试写入日志文件时权限被拒绝
【发布时间】:2013-03-19 05:33:08
【问题描述】:

在我的 C/C++ 程序中写入日志文件时出现问题。 下面是出现问题的代码示例

EnterCriticalSection(&critical);
printf("\nWaiting for a connection on TCP port %d (nbr of current threads = %d)...\n", pServer->TCPServerPort, (*pServer->lChildInfo));
AddLog("Waiting for a connection on TCP port %d (nbr of current threads = %d)...", pServer->TCPServerPort, (*pServer->lChildInfo));
LeaveCriticalSection(&critical);

// creating variables to be passed to the thread
struct*ThreadData = (struct*) malloc(sizeof(struct));
ThreadData->csock = (int*)malloc(sizeof(int));
memcpy(&ThreadData->pServer,&pServer,sizeof(pServer));

if((*ThreadData->csock = accept( pServer->ListenSocket, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){

    ThreadData->dwIP = sadr.sin_addr.s_addr;
    ThreadData->wPort = sadr.sin_port;

    printf("Received connection from %s:%d \n",inet_ntoa(sadr.sin_addr), ntohs(sadr.sin_port));
    AddLog("Received connection from %s:%d ",inet_ntoa(sadr.sin_addr), ntohs(sadr.sin_port));

AddLog 是我为了写入文件而编写的函数:

FILE *fichier = NULL;
va_list ap;
va_start(ap, log); 
//fichier = fopen("log.log","a");
fichier = _fsopen("log.log", "a", SH_DENYNO);
if (fichier == NULL)  
    printf("Error log: %d (%s)\n", errno, strerror(errno));
else {  
    fprintf(fichier,":");
    vfprintf(fichier, log, ap);
    fprintf(fichier,"\n");
    va_end(ap);
    fclose(fichier);    
}

我无法真正解释的是,第一个 AddLog(“Waiting for....”以及之前的所有..)已正确写入文件。但是当我尝试连接时,随后的日志(从...接收连接)没有写入文件,我总是收到错误 13“权限被拒绝”。 我在文件中使用了 chmod 777,我也尝试了 _fsopen 函数,一旦我进入线程,我仍然会收到这个错误。 如果有人有任何想法,那将很有帮助。 谢谢大家

【问题讨论】:

  • 向我们展示完整的示例程序,它可能有助于找到问题。
  • 由于您最初的AddLog() 调用由临界区保护,我怀疑所有其他实例也应该如此。不确定这是否是您的问题,但这是 a 问题。此外,您可能应该将AddLog() 中的va_start() 移动到else 子句中,否则可能永远不会调用匹配的va_end() - 这是否是一个问题可能取决于实现,尽管...

标签: c windows file permissions fopen


【解决方案1】:

我不知道是不是问题,但我建议在 _fsopen 中使用“a+” 对于共享追加,因为线程另一个进程。

【讨论】:

    【解决方案2】:

    我不知道它是否仍然相关,但我必须建议您使用更好的解决方案: (几天前我遇到了同样的问题,解决方案很简单) 我刚刚实现了一个共享队列,之后我添加到队列中的所有日志我运行了一个工作线程,它正在检查队列并在队列不为空时写入文件。

    我希望它能帮助你度过美好的一天:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 2016-05-27
      • 2015-08-02
      • 2022-09-29
      • 2015-08-24
      • 2018-02-20
      • 2011-12-23
      相关资源
      最近更新 更多