gpt4 book ai didi

c - 读取和写入操作得到错误的 fd 并且没有这样的文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:58 25 4
gpt4 key购买 nike

我有这个 C 程序。我有两个进程,父子,并使用信号量使它们一次同步一个。父亲必须写 (n) 个数字,在本例中是十个,总是在打开文件的第一个字节中,儿子必须读取它。问题是,当我打印结果时,写入(父亲)的文件描述符错误,而读取(儿子)则没有这样的文件。你能帮我吗??谢谢

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define FILENAME "test.txt"
#define MUTEX "/mutex"
#define READ "/read"
#define WRITE "/write"

int main(int argc, char *argv[]){
int i, pid, n=10, fd, x;
int nread, nwrite;
char c = 'a';
sem_t *mutex, *reader, *writer;

//fd = open(FILENAME, O_CREAT | O_TRUNC, 0666);
mutex = sem_open(MUTEX, O_CREAT, 0666, 1);
reader = sem_open(READ, O_CREAT, 0666, 0);
writer = sem_open(WRITE, O_CREAT, 0666, 1);
pid = fork();
fd = open(FILENAME, O_CREAT | O_TRUNC, 0777);
if(fd < 0){
perror("Open FILE error");
exit(-1);}
if(pid == 0){ // son
do{
sem_wait(reader); // si può leggere???
sem_wait(mutex);
lseek(fd, 0, SEEK_SET);
nread = read(fd, &x, sizeof(int));
if(nread <=0)
perror("Read error");
printf("Son has read (%d byte) = %d\n", nread, x);
fflush(NULL);
sem_post(mutex);
sem_post(writer);
}
while(x != (n-1));
exit(0);
}
else{
for(i=0; i<n; i++){
sem_wait(writer); // can I write??
sem_wait(mutex);
lseek(fd, 0, SEEK_SET);
nwrite = write(fd, &c, sizeof(char));
if(nwrite <= 0)
perror("nwrite error");
printf("Father has written (%d byte) %d\n", nwrite, i);
fflush(NULL);
sem_post(mutex);
sem_post(reader); // it's possible to read
}
//wait(NULL);
}
sem_unlink(MUTEX);
sem_unlink(READ);
sem_unlink(WRITE);
//remove(FILENAME);

exit(0);
}

最佳答案

首先,您在没有指定 o_flag 的情况下打开了文件。这实际上是未定义的行为 ( "Applications shall specify exactly one of .... O_RDONLY .... O_WRONLY .... O_RDWR" ),但出于实际目的意味着文件以只读打开。

因此父级的写操作因 EBADF 而失败。无法写入只读文件!

其次, child 的错误检查不正确。 read()成功时可能返回零,在这种情况下,perror() 查询的 errno 不能保证有意义。您的意思是检查返回值是否小于零,而不是小于或等于零。

关于c - 读取和写入操作得到错误的 fd 并且没有这样的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com