23,116
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<stdbool.h>
#include<fcntl.h>
#include<pthread.h>
#include<errno.h>
#define FIFO_READ "readfifo"
#define FIFO_WRITE "writefifo"
#define BUFSIZE 1024
bool connect=true;
void *read_from(void *arg)
{
int rfd=-1;
char buf[BUFSIZE]={0};
int i;
printf("waiting...\n");
while((rfd=open(FIFO_READ,O_RDONLY))==-1)
{
sleep(1);
}
while(connect)
{
int len=read(rfd,buf,BUFSIZE);
if(len>0)
{
buf[len]='\0';
if(strncmp(buf,"byebye",6)==0)
{
printf("disconnection\n");
connect=false;
break;
}
}
printf("Other Side:%s\n",buf);
printf("me:");
fflush(stdout);
}
close(rfd);
return NULL;
}
void *write_to(void *arg)
{
int wfd;
char buf[BUFSIZE]={0};
int len;
mode_t omd,nmd;
nmd=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
//omd=umask(nmd);
if(!mkfifo(FIFO_WRITE,S_IFIFO|0666))
{
printf("create fifo:%s error,because %s\n",FIFO_WRITE,strerror(errno));
exit(EXIT_FAILURE);
}
//umask(omd);
//chmod(FIFO_WRITE,nmd);
wfd=open(FIFO_WRITE,O_WRONLY);
if(wfd==-1)
{
printf("open fifo:%s error,becase %s\n",FIFO_WRITE,strerror(errno));
exit(EXIT_FAILURE);
}
while(connect)
{
int n;
printf("me:");
n=read(STDIN_FILENO,buf,BUFSIZE);
if(n<0)
{
printf("read error\n");
exit(EXIT_FAILURE);
}
buf[n]='\0';
if(strncmp(buf,"byebye",6)==0||!connect)
{
write(wfd,buf,n);
close(wfd);
unlink(FIFO_WRITE);
exit(EXIT_SUCCESS);
}
write(wfd,buf,n);
fflush(stdout);
}
return NULL;
}
int main(void)
{
pthread_t thIDr,thIDw;
pthread_create(&thIDr,NULL,&read_from,NULL);
pthread_create(&thIDw,NULL,&write_to,NULL);
pthread_join(thIDr,NULL);
pthread_join(thIDw,NULL);
return 0;
}
if(mkfifo(FIFO_WRITE,S_IFIFO|0666))
{
printf("create fifo:%s error,because %s\n",FIFO_WRITE,strerror(errno));
exit(EXIT_FAILURE);
}
这里改成这样才是正确逻辑。我这样改了以后,错误提示变成::create fifo:writefifo error,because Operation not permitted
没有权限。我改成ROOT执行都一样。