我有以下代码,其中我正在创建一些进程,然后在控制台上打印一些内容,并将一些内容写入文件。问题是我在控制台上得到了一次打印,但是当我运行代码时我得到了多个文件写入。我无法弄清楚是什么原因造成的,以及如何让它按我的意图工作。我希望该行也只写入文件一次。
代码:
#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