【发布时间】:2018-11-13 16:21:23
【问题描述】:
我正在尝试用 fopen 打开一个文件,fork 当前进程并让子进程在文件上写一些东西;当子进程退出时,父进程应该读取文件的内容,但它读取“null”,即使文件已正确写入。没有错误报告。 这是我的代码:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
FILE * sharedFile;
char *fileContent;
if((sharedFile = fopen("testFile.txt","w+")) == NULL){
fprintf(stderr,"Error while opening the file: %s",strerror(errno));
return 0;
}
pid_t pid = fork();
if(pid == 0){
//Child
fprintf(sharedFile,"%s",argv[1]);
exit(0);
}
else{
//Parent
wait(NULL);
if(fscanf(sharedFile,"%s",fileContent) < 0){
fprintf(stderr,"Error while reading file: %s",strerror(errno));
return 0;
}
fprintf(stdout,"File content: %s",fileContent); //Outputs "File content: (null)"
fclose(sharedFile);
}
}
奇怪的是,如果我在分叉后再次打开父代码中的文件,输出是正确的。 可能是什么问题?
【问题讨论】:
-
当
fileContent是一个未初始化的指针时任何工作都是一个意外。这就是未定义行为的美妙之处。