[英]Reading and Writing to a Named Pipe
我正在使用兩個程序。 customer.c程序將int寫入命名管道, bank.c讀取管道並打印int。 客戶將選擇兩個命名管道“ atm1”和“ atm2”之一。
最終,我想運行兩個customer.c程序,每個程序同時運行一個,但是在寫入和讀取命名管道時遇到一些問題。
如果我只運行bank.c和一個customer.c,則不會得到任何輸出。
如果我運行bank.c和兩個customer.c,則輸出並不總是打印出來或出現故障。
我嘗試使用fsync()進行刷新,但這也不起作用。
客戶
int main(int argc, char *argv[]){
int fd, num =0;
if((fd = open(argv[1], O_WRONLY)) == -1){
...
}
while(1){
printf("Enter a integer:\n");
scanf("%d", &num);
if(num < 0){
break;
}
if(write(fd, &num, sizeof(num)) <= 0){...}
fsync(fd);
}
close(fd);
return 0;
}
銀行
int main(){
int fd, sd, num=0, sret, fret, maxfd;
//fd_set readfds;
//struct timeval timeout;
if(mkfifo("atm1", 0666) == -1){...}
if(mkfifo("atm2", 0666) == -1){...}
if((fd = open("atm1", O_RDONLY)) == -1){...}
if((sd = open("atm2", O_RDONLY)) == -1){...}
while(1){
if((sret = read(sd, &num, sizeof(num))) > 0){
printf("%d\n", num);
}
if((fret = read(fd, &num, sizeof(num))) > 0){
printf("%d\n", num);
}
if(sret <= 0 && fret <= 0){
break;
}
}
close(fd);
close(sd);
return 0;
}
有指針嗎?
您需要使多線程服務器同時進行多次接收。 並要求檢查管道名稱是否已存在。
空白
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
void *client(void *data)
{
char *pname = (char*) data ;
int sd =0 ;
int num ;
int sret=0 ;
if((sd = open(pname, O_RDONLY)) == -1) {
printf("open failed:%s\n", pname) ;
return NULL ;
}
printf("client[%d] start\n", sd) ;
while(1){
num=0 ;
if((sret = read(sd, &num, sizeof(num))) > 0){
printf("[%d] recv:%d\n", sd, num);
}
if(sret <= 0) {
break;
}
}
close(sd);
printf("client[%d] end\n", sd) ;
return NULL;
}
int main(){
int status ;
pthread_t t1, t2 ;
if(mkfifo("atm1", 0666) == -1) {
printf("mkfifio failed : %d\n", errno) ;
if (errno==EEXIST ) {
printf("already exist. ignore\n") ;
}
else
return -1;
}
if(mkfifo("atm2", 0666) == -1) {
printf("mkfifio failed2 : %d\n", errno) ;
if (errno==EEXIST ) {
printf("already exist. ignore\n") ;
}
else
return -1;
}
pthread_create(&t1, NULL, client, (void*)"atm1") ;
pthread_create(&t2, NULL, client, (void*)"atm2") ;
pthread_join(t1, (void**)&status) ;
pthread_join(t2, (void**)&status) ;
return 0;
}
您可以同時訪問atm1和atm2。 ./customer atm1 ./customer atm2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.