/*
* Linux下C语言实现的简单使用线程向FIFO里写入与读取数据的例子
*/
#include < stdio.h >
#include < fcntl.h >
#include < stdlib.h >
#include < pthread.h >
#include < unistd.h >
pthread_t ntid;
struct c_stat
{
char c_r;
char *c_pid;
} ;
void * p_c( void * arg)
{
struct c_stat *tmp;
char fifoname[15];
tmp=(struct c_stat *) arg;
printf("New thread ");
if (tmp->c_r == '1')
{
printf("请求写入数据 ");
snprintf(fifoname, 15, "/tmp/fifo.%s", tmp->c_pid);
mkfifo(fifoname, O_RDWR | O_NONBLOCK);
int fd_to = open(fifoname, O_RDWR | O_NONBLOCK);
write(fd_to, "niejun", 6);
sleep(1);
}
printf("%c ", tmp->c_r);
printf("%s ", tmp->c_pid);
return ((void *) 0);
}
int main( void )
{
char in_buf[7];
char *str_pid;
unlink("/tmp/fifo.common");
mkfifo("/tmp/fifo.common", O_RDWR | O_NONBLOCK);
int fd_common = open("/tmp/fifo.common", O_RDWR | O_NONBLOCK);
for (;;)
{
int r = read(fd_common, in_buf, 6);
in_buf[6] = '';
struct c_stat stat;
str_pid = in_buf + 1;
stat.c_r = in_buf[0];
stat.c_pid = str_pid;
if (in_buf[0] == '1') {
int p_creat = pthread_create(&ntid, NULL, p_c, &stat);
printf("%s ", in_buf);
in_buf[0] = '2';
printf("%d ", atoi(str_pid));
}
usleep(1000);
}
close(fd_common);
}
* Linux下C语言实现的简单使用线程向FIFO里写入与读取数据的例子
*/
#include < stdio.h >
#include < fcntl.h >
#include < stdlib.h >
#include < pthread.h >
#include < unistd.h >
pthread_t ntid;
struct c_stat
{
char c_r;
char *c_pid;
} ;
void * p_c( void * arg)
{
struct c_stat *tmp;
char fifoname[15];
tmp=(struct c_stat *) arg;
printf("New thread ");
if (tmp->c_r == '1')
{
printf("请求写入数据 ");
snprintf(fifoname, 15, "/tmp/fifo.%s", tmp->c_pid);
mkfifo(fifoname, O_RDWR | O_NONBLOCK);
int fd_to = open(fifoname, O_RDWR | O_NONBLOCK);
write(fd_to, "niejun", 6);
sleep(1);
}
printf("%c ", tmp->c_r);
printf("%s ", tmp->c_pid);
return ((void *) 0);
}
int main( void )
{
char in_buf[7];
char *str_pid;
unlink("/tmp/fifo.common");
mkfifo("/tmp/fifo.common", O_RDWR | O_NONBLOCK);
int fd_common = open("/tmp/fifo.common", O_RDWR | O_NONBLOCK);
for (;;)
{
int r = read(fd_common, in_buf, 6);
in_buf[6] = '';
struct c_stat stat;
str_pid = in_buf + 1;
stat.c_r = in_buf[0];
stat.c_pid = str_pid;
if (in_buf[0] == '1') {
int p_creat = pthread_create(&ntid, NULL, p_c, &stat);
printf("%s ", in_buf);
in_buf[0] = '2';
printf("%d ", atoi(str_pid));
}
usleep(1000);
}
close(fd_common);
}