-1

练习很简单。父进程让我将我的名字和姓氏写在一个文件中。子进程等待 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 秒,它会显示文件内容(基本上是随机字符)。

4

2 回答 2

4

您正在主进程中关闭文件,然后您想在子进程中重用相同的指针。这是不可能的。您需要在子进程中重新打开文件。

所以,你需要在sleep()调用之后写这个:

file = fopen("dati.txt", "r");

您也不需要#rewind()函数调用,因为您将回到文件的开头。

更新:问题是这w+意味着

写入/更新:创建一个空文件并打开它进行更新

所以,你的文件被删除了。和r模式,它工作得很好。

PS:顺便说一句,你不应该cstdio在 C 程序中使用,只使用标准stdio.h头文件。还有一个编译错误,因为您正在重新声明循环变量i

于 2015-02-09T15:07:19.383 回答
0

You need to fopen file after fork() both for parent and child separately:

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 */
    ...
}

With this change it will work. Mind that, only the parent process is actively connected to your console - the output of child will show after 5 seconds and might appear after parent process exits (due to no call to wait). So you can see "Father exists" message and get console prompt before child will show any output.

于 2015-02-09T16:52:02.983 回答