1

在我的 C/C++ prog 中写入日志文件时出现问题。这是发生问题的代码示例

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 (“等待......”和之前的所有......)被正确地写入文件中。但是当我尝试连接时,随后的日志(从...接收连接)没有写入文件,我总是收到错误 13“权限被拒绝”。我在文件中使用了 chmod 777,我还尝试了 _fsopen 函数,一旦我进入线程,我仍然会收到此错误。如果有人有任何想法,那将很有帮助。谢谢大家

4

2 回答 2

0

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

我希望它有助于度过美好的一天:)

于 2013-11-14T21:33:16.527 回答
0

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

于 2013-07-20T22:02:33.607 回答