这是我的代码中感兴趣的部分(半模化,因为它有点乱): Archive.c:
int main(int argc, char* argv[])
{
pthread_t* thread_tid;
pthread_create(&thread_tid, NULL, wthread_boss_body, NULL);
xpthread_join(tid_sig_handler, NULL, QUI);
return 0;
}
void* wthread_boss_body(void* v)
{
dati* tdati = (dati*)v;
int fd = open("caposc",O_RDONLY);
if(fd<0) error handling...
while(true)
{
char test[7];
puts("provo a leggere...\n");
read(fd, test, 7);
printf("ecco qua: %s", test);
sleep(1);
}
pthread_exit(NULL);
}
Server.py:
FIFOcaposc = 'caposc'
def main():
try:
os.mkfifo(FIFOcaposc)
except FileExistsError:
pass
except OSError as e:
print(f"Creazione FIFO {FIFOcaposc} fallita: {e}")
exit(1)
try:
caposc = open(FIFOcaposc, 'w')
print("caposc aperta\n")
except OSError as e:
print(f"Apertura FIFO {FIFOcaposc} fallita: {e}")
exit(1)
while(True):
print("writing...\n")
print(f"{caposc.write('abcdefg')}\n")
time.sleep(1)
caposc.close()
capolet.close()
os.unlink(FIFOcaposc)
os.unlink(FIFOcapolet)
main()
同时运行这两个文件时,server.py会一直循环,并按预期在FIFO上写入(WRITE返回值始终为7),但achve.c在第一个周期的读操作中保持不变,再也不会返回.据我所知,在FIFO上有可供读取的内容之前,读取器不会返回.但既然看起来真的有什么可读的,我的脑子就被炸开了.
我又做了几个愚蠢的节目,我做了这个,这个效果很好: Test.c:
void* thread_body(void* v);
int main(int argc, char* argv[])
{
pthread_t t1;
pthread_create(&t1, NULL, &thread_body, NULL);
pthread_join(t1, NULL);
}
void* thread_body(void* v)
{
int fd = open("pipeprova", O_RDONLY);
char stringa[8];
while(true)
{
int e = read(fd, &stringa, 7);
if(e == 0) puts("no");
stringa[7] = '\0';
printf("%s\n", stringa);
}
pthread_exit(NULL);
}
Testpy.py:
try:
os.mkfifo("pipeprova")
except FileExistsError:
pass
except OSError as e: # TODO: verifica che OSError non comprenda FileExistsError
print(f"Creazione FIFO fallita: {e}")
exit(1)
try:
fifo = open("pipeprova", 'w')
print("aperta\n")
except OSError as e:
print(f"Apertura FIFO fallita: {e}")
exit(1)
while(True):
print(f"{fifo.write('abcdefg')}\n")
fifo.close();
我真的不明白哪里错了,经过长时间的研究,我发现了一些能让我的代码正常工作的东西,而在我的server.py中,它是有效的:
while(True):
caposc = open(FIFOcaposc, 'w')
print("writing...\n")
print(f"{caposc.write('abcdefg')}\n")
time.sleep(1)
caposc.close()
我真的需要每次都打开和关闭系统调用吗?为什么?有没有更有效的方法?