【发布时间】:2013-09-25 04:59:27
【问题描述】:
我有以下代码,其中我正在创建一些进程,然后在控制台上打印一些内容,并将一些内容写入文件。问题是我在控制台上得到了一次打印,但是当我运行代码时我得到了多个文件写入。我无法弄清楚是什么原因造成的,以及如何让它按我的意图工作。我希望该行也只写入文件一次。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include "server.h"
#define QUELEN 256
main(int argc, char *argv[])
{
struct sockaddr_in manager, client;
struct hostent *cp;
int sockdescriptor, td;
int len;
int j;
pid_t pid;
int dummy;
char str1[32], str2[32];
FILE* fp;
FILE *output_fp;
if ((output_fp = fopen("dummy.out", "w")) != NULL){
}
else{
printf("output file not created\n");
}
/* THIS IS WHERE THE PROBLEM IS */
printf("just print this once on console\n");
fprintf(output_fp, "just write this once to the file...\n");
/****************************** Forking Client Subprocesses ***********************************/
/* */
/* */
for(j = 0; j < 4 ; j++){
if((pid = fork()) == 0){ // child process
// dosomething();
exit(0); // terminate child process
}
} // end of the forking for loop
/* */
/* */
/**********************************************************************************************/
listen(sockdescriptor, QUELEN); // listening for incoming connections here
while(1) {
len = sizeof(struct sockaddr_in);
td = accept(sockdescriptor, (struct sockaddr *) &client, &len);
if((pid = fork()) == 0){ // child process
close(sockdescriptor); //closing listening socket
cp = gethostbyaddr((char *) &client.sin_addr, sizeof(struct in_addr), AF_INET);
close(td); // client req. processed, close this socket
close(sockdescriptor);
exit(0);
} // end of ((pid = fork()) == 0)
close(td);
} // end of while loop
} // end of main
文件中的输出:
just write this once to the file...
just write this once to the file...
just write this once to the file...
just write this once to the file...
命令提示符的输出:
just print this once on console
【问题讨论】:
-
是的,刚刚做了这个,现在工作正常。有人已经把这个解决方案记下来了,但似乎他们在我回应之前就删除了它。无论如何,我得到了他们的建议
sprintf(str1, "just print this once in file\n"); fprintf(output_fp, str1); setvbuf(output_fp, str1, _IOLBF, 1024); -
那么为什么不自己添加一个答案呢?
-
@ZahaibAkhtar,自己添加一个答案。你必须;)
-
好吧,我只是把我的答案写下来,因为有 8 小时的限制,所以不能早点这样做。