【发布时间】:2019-04-16 16:34:36
【问题描述】:
解决这个问题的正确方法是什么?
例如,我有一个名为 write.c 的程序,它有 4 个子进程,并且子进程将它们的 PID 写入单个全局命名管道。
另一个名为read.c的程序应该读取这个PID。
我有一个像下面这样的方法,但是这种方法有一些问题。它不能读取所有的 PID,有时是 3 个,有时是 2 个。我认为有一个同步问题,我该如何解决这个问题? :
writer.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
int fd;
char * myfifo = "/tmp/myfifo"; //FIFO file
char buffer[50];
mkfifo(myfifo, 0666); //creating the FIFO
for(int i=0;i<4;i++){ //creating 4 child process
if(fork() == 0) {
fd = open(myfifo, O_WRONLY); //each child process opens the FIFO for writing their own PID.
sprintf(buffer, "%d", getpid()); //each child process gets pid and assign it to buffer
printf("write:%s\n", buffer); // each child process prints to see the buffer clearly
write(fd, buffer, strlen(buffer)+1); //each child process writes the buffer to the FIFO
close(fd);
exit(0);
}
}
for(int i=0;i<4;i++) { //waiting the termination of all 4 child processes.
wait(NULL);
}
//parent area
}
reader.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char **argv) {
int fd1;
// FIFO file path
char * myfifo = "/tmp/myfifo";
// Creating the named file(FIFO)
mkfifo(myfifo, 0666);
char str1[80]; //str2[80];
while (1)
{
// First open in read only and read
fd1 = open(myfifo,O_RDONLY);
read(fd1, str1, 80);
// Print the read string and close
printf("read: %s\n", str1);
close(fd1);
}
}
【问题讨论】:
-
在第一个之后 mkfifo 没有得到 EEXIST 吗?
-
应该,@stark,但这是一个可以忽略的错误。更成问题的是,没有测试该函数或其他任何可能的其他错误。
-
是的。至少需要检查 mkfifo 上的错误并打开。
标签: c multiprocessing ipc named-pipes fifo