【发布时间】:2017-10-05 02:05:44
【问题描述】:
我目前正在研究 C 的多线程,但对于我们的命名管道 excersize,我不太了解。
我们期望执行文件搜索系统的实现,该系统使用一个进程查找文件并添加到缓冲区,第二个进程应该从第一个线程的线程中获取文件名,在该文件中找到搜索查询并将位置返回给第一个进程通过管道。我做了几乎所有的事情,但我很困惑如何在两个进程之间进行通信。
这是我进行通信的代码:
main.c
void *controller_thread(void *arg) {
pthread_mutex_lock(&index_mutex);
int index = t_index++; /*Get an index to thread*/
pthread_mutex_unlock(&index_mutex);
char sendPipe[10];
char recvPipe[10];
int fdsend, fdrecv;
sprintf(sendPipe, "contrl%d", (index+1));
sprintf(recvPipe, "minion%d", (index+1));
mkfifo(sendPipe, 0666);
execlp("minion", "minion", sendPipe, recvPipe, (char*) NULL);
if((fdsend = open(sendPipe, O_WRONLY|O_CREAT)) < 0)
perror("Error opening pipe");
if((fdrecv = open(recvPipe, O_RDONLY)) < 0)
perror("Error opening pipe");
while(1) {
char *fileName = pop(); /*Counting semaphore from buffer*/
if(notFile(fileName))
break;
write(fdsend, fileName, strlen(fileName));
write(fdsend, search, strlen(search));
char place[10];
while(1) {
read(fdrecv, place, 10);
if(notPlace(place)) /*Only checks if all numeric*/
break;
printf("Minion %d searching %s in %s, found at %s\n", index,
search, fileName, place);
}
}
}
从我找到的网上资源来看,我认为这是在main里面处理fifo的方法。我试图编写一个测试奴才只是为了确保它可以工作,所以在这里
minion.c
int main(int argc, char **argv) {
char *recvPipe = argv[1];
char *sendPipe = argv[2];
char fileName[100];
int fdsend, fdrecv;
return 0;
fdrecv = open(recvPipe, O_RDONLY);
mkfifo(sendPipe, 0666);
fdsend = open(sendPipe, O_WRONLY|O_CREAT);
while(1) {
read(fdrecv, fileName, 100);
write(fdsend, "12345", 6);
write(fds, "xxx", 4);
}
return 0;
}
当我以这种方式运行时,如果我将 O_NONBLOCK 更改为打开模式,线程会被阻塞并且不打印任何响应。然后它打印“错误打开管道没有这样的设备或地址”错误,所以我知道我无法在 minion 中打开 recvPipe 但我不知道是什么错误
【问题讨论】:
标签: c multithreading named-pipes fifo