在c中的fork()之后返回null的fprintf
我试图用fopen打开一个文件,分叉当前进程,让子进程在文件上写点东西;当子进程退出时,父进程应该读取文件的内容,但它读取“null”,即使文件已正确写入。未报告任何错误。 这是我的密码:在c中的fork()之后返回null的fprintf,c,file,process,fork,C,File,Process,Fork,我试图用fopen打开一个文件,分叉当前进程,让子进程在文件上写点东西;当子进程退出时,父进程应该读取文件的内容,但它读取“null”,即使文件已正确写入。未报告任何错误。 这是我的密码: #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h>
#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);
}
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
文件*共享文件;
字符*文件内容;
if((sharedFile=fopen(“testFile.txt”,“w+”)==NULL){
fprintf(stderr,“打开文件时出错:%s”,strerror(errno));
返回0;
}
pid_t pid=fork();
如果(pid==0){
//孩子
fprintf(共享文件,“%s”,argv[1]);
出口(0);
}
否则{
//母公司
等待(空);
如果(fscanf(共享文件,“%s”,文件内容)<0){
fprintf(stderr,“读取文件时出错:%s”,strerror(errno));
返回0;
}
fprintf(标准输出,“文件内容:%s”,文件内容);//输出“文件内容:(null)”
fclose(共享文件);
}
}
奇怪的是,如果我在fork之后再次打开父代码中的文件,则输出是正确的。
可能是什么问题?
fileContent
未分配任何空间。也许你可以这样做
char fileContent[101];
...
if (fscanf(sharedFile,"%100s",fileContent) != 1) // Prevent buffer overflows. Should return one when successful.
谢谢你的回答!我试过你的建议,但现在它打印“File content:success”@diable:还应该打印什么?该(“
success
”)可能是文件中的第一个单词。@JonathanLeffler它应该打印文件的内容,该内容由子进程设置。我尝试在fork之后的父代码中使用fopen再次打开该文件,并且输出是所需的one@Stubborn当前位置不,不可能发生这种情况。这些进程共享相同的打开文件描述(不同于打开文件描述符)。当子对象写入时,它也会移动父对象的当前位置。这些文件的关系比你想象的要密切得多。在读取之前,您的父进程必须搜索到文件的开头(fseek(sharedFile,0,seek\u SET)
)。如果有更多的互动,这些过程就必须更仔细地协调。您有最简单的交互-一个写一次,另一个读一次。@顽固:您可以阅读POSIX规范中的基本问题。。当fileContent
是未初始化的指针时,任何工作都是意外的。这就是未定义行为的美妙之处。