- 论坛徽章:
- 0
|
第一个程序:
//filename:peter.c
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
int main(void)
{
char write_fifo_name[] = "read-fifo";
char read_fifo_name[] = "write-fifo";
int write_fd = 0;
int read_fd = 0;
char buf[256] = { "\0"};
int len = 0;
int ret = mkfifo(write_fifo_name,S_IRUSR | S_IWUSR );
printf("ret of peter.c is %d\n",ret);
if(ret == -1)
{
printf("Fail to create FIFO %s: %s",write_fifo_name,strerror(errno));
exit(-1);
}
while((read_fd = open(read_fifo_name, O_RDONLY)) == -1)
{
sleep(1);
}
write_fd = open(write_fifo_name, O_WRONLY);
if(write_fd == -1)
{
printf("Fail to open FIFO %s: %s",write_fifo_name, strerror(errno));
exit(-1);
}
while(1)
{
len = read(read_fd, buf, 256);
if(len > 0)
{
buf[len] = '\0';
printf("Lucy: %s\n",buf);
}
printf("Peter: ");
fgets(buf,256,stdin);
buf[strlen(buf) - 1] = '\0';
if(strncmp(buf,"quit",4) == 0)
{
close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd,buf,strlen(buf));
}
}
第二个程序:
//filename : lucy.c
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
char write_fifo_name[] = "write-fifo";
char read_fifo_name[] = "read-fifo";
int write_fd = 0;
int read_fd = 0;
char buf[256] = { "\0"};
int len = 0;
struct stat stat_buf;
int ret = 0;
ret = mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);
printf("ret of lucy.c is %d",ret);
if(ret == -1)
{
printf("Fail to create FIFO %s: %s",write_fifo_name, strerror(errno));
exit(-1);
}
write_fd = open(write_fifo_name, O_WRONLY);
if(write_fd == -1)
{
printf("Fail to open FIFO %s: %s", write_fifo_name, strerror(errno));
exit(-1);
}
while((read_fd = open(read_fifo_name, O_WRONLY)) == -1)
{
sleep(1);
}
while(1)
{
printf("Lucy: ");
fgets(buf,256,stdin);
buf[strlen(buf) - 1] = '\0';
if(strncmp(buf,"quit",4) == 0)
{
close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd, buf, strlen(buf));
len = read(read_fd,buf,256);
if(len > 0)
{
buf[len] = '\0';
printf("Peter: %s\n",buf);
}
}
}
这两个程序进行进程间通信,但第二个程序在mkfifo时停住不前进,请问题出在什么地方了?
有什么办法解决?
[ 本帖最后由 zhanglupanda 于 2007-7-23 10:54 编辑 ] |
|