在fork-C中写和读
这个练习很简单。父亲程序让我把我的名字和姓氏写在一个文件里。子进程等待5秒,然后读取并显示它。我无法使用在fork-C中写和读,c,fork,fgets,fputs,C,Fork,Fgets,Fputs,这个练习很简单。父亲程序让我把我的名字和姓氏写在一个文件里。子进程等待5秒,然后读取并显示它。我无法使用#wait()函数 #include <cstdlib> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char** argv) { char name[20]; ch
#wait()
函数
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv) {
char name[20];
char surname[20];
char outp[50];
// The file pointer
FILE *file;
// Open the file in write mode
file = fopen("dati.txt", "w+");
pid_t pid;
pid=fork();
if(pid>0){
printf("Father");
printf("Insert name: ");
scanf("%s",name);
for (int i=0; i<strlen(name); i++) {
if (i==0) {
if (name[i]>='a' && name[i]<='z')
name[i]-=32;
} else {
if (name[i]>='A' && name[i]<='Z')
name[i]+=32;
}
}
printf("Insert surname: ");
scanf("%s", surname);
for (int i=0; i<strlen(name); i++){
if (i==0){
if (surname[i]>='a' && surname[i]<='z')
surname[i]-=32;
} else {
if (surname[i]>='A' && surname[i]<='Z')
surname[i]+=32;
}
}
fputs(name, file);
fputs(" ",file);
fputs(surname, file);
printf("Father exits");
fclose(file);
exit(0);
}else{
sleep(5);
// position to the start of the file
rewind(file);
fgets(outp, 50, file);
printf("Read string: %s", outp);
fclose(file);
exit(0);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,字符**argv){
字符名[20];
查氏[20];
字符输出[50];
//文件指针
文件*文件;
//以写模式打开文件
file=fopen(“dati.txt”,“w+”);
pid_t pid;
pid=fork();
如果(pid>0){
printf(“父亲”);
printf(“插入名称:”);
scanf(“%s”,名称);
对于(int i=0;i='a'&&name[i]='a'&&name[i]您正在关闭主进程中的文件,然后希望在子进程中重用同一指针。这是不可能的。您需要在子进程中重新打开该文件
因此,您需要在调用sleep()
后编写此代码:
file = fopen("dati.txt", "r");
您也不需要调用#rewind()
函数,因为您将回到文件的开头
更新:问题在于w+
意味着
写入/更新:创建一个空文件并打开它进行更新
因此,您知道该文件已被擦除。使用r
模式,它工作正常
PS:顺便说一句,在C程序中不应该使用cstdio
,只使用标准的stdio.h
头文件。还有一个编译错误,因为您正在重新说明循环变量i
您需要在fopen
文件之后fork()
分别针对父级和子级:
if (pid > 0) {
/* Parent process */
file = fopen("dati.txt", "w+");
/* write to file */
...
} else {
/* child process */
sleep(5);
file = fopen("dati.txt", "r");
/* read from file */
...
}
通过此更改,它将起作用。请注意,只有父进程主动连接到您的控制台-子进程的输出将在5秒后显示,并且可能在父进程退出后显示(由于没有调用wait
)。因此您可以看到“父进程存在”在子进程将显示任何输出之前,请发送消息并获取控制台提示。尝试使用缩进英语,我不知道这是哪种语言,您不需要在每行后面添加空行,这实际上会降低代码的可读性。它不起作用。相同的结果。父进程起作用,子进程不起作用。它实际上不会启动事件如果我在第5秒之前插入我的姓名。哦,还有一件事,删除那些exit(0)
调用。仍然是一样的。我在子进程和父进程中添加了file=fopen和fclose,并删除了exit(0)。我刚刚测试了这个。实际上,您不需要在pid>0
之后使用第一个fopen
,就像在fork
之前一样,它仍然是父进程。所需的更改是第二个fopen
中的r
。您忘记了引号。您不需要打开文件进行写入在这两个过程中(如果在fork之前使用fopen,您将拥有这两个过程)。这样,父级和子级所做的工作更具可读性。