练习很简单。父进程让我将我的名字和姓氏写在一个文件中。子进程等待 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];
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;
}
如果我在第 5 秒之前插入姓名和姓氏,程序会写入它们,但不会显示它们。否则,如果我写了名称并“不小心”等待第 5 秒,它会显示文件内容(基本上是随机字符)。