- 论坛徽章:
- 0
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
typedef struct file_node{
int r_pipe;
int w_pipe;
int fd;
}file_node;
char *file[] = {"./a","./b","./c","./d"};
file_node node_list[4];
void *thread_func(void *arg);
int main()
{
int *num, i;
int sockpair[2];
memset(node_list, 0, sizeof(node_list));
//打开文件,构建线程间管道
for (i=0; i<4; i++) {
if (socketpair(AF_UNIX,SOCK_STREAM, 0, sockpair)) {
printf("socketpair error !\n");
exit(1);
}
node_list[i].w_pipe = sockpair[0];
if (i != 3)
node_list[i+1].r_pipe = sockpair[1];
else
node_list[0].r_pipe = sockpair[1];
node_list[i].fd = open(file[i], O_CREAT | O_WRONLY| O_APPEND, S_IRUSR|S_IWUSR);
if (node_list[i].fd < 0) {
printf("open fd error , exit !\n");
exit(1);
}
}
//创建线程
for(i=0;i<4; i++) {
num =(int*)malloc(sizeof(int));
*num = i;
pthread_create(NULL, NULL, thread_func, num);
}
pause();
}
void *thread_func(void *arg)
{
pthread_t pid;
char buf[100];
int w_fd, num;
num = *(int*)arg;
free(arg);
pid = pthread_self();
pthread_detach(pid);
sprintf(buf, "%d", num+1);
w_fd = node_list[num].fd;
for (; ; )
{
//写文件
if (write(w_fd, (void*)buf, strlen(buf)) != strlen(buf)) {
printf("write something to file error !\n");
break;
}
//通知下一个线程写
if (write(node_list[num].w_pipe, (void*)&w_fd, sizeof(int)) != sizeof(int)) {
printf("write fd to pipe error !\n");
break;
}
if (read(node_list[num].r_pipe, &w_fd, sizeof(int)) != sizeof(int)) {
printf("read fd from pipe error !\n");
break;
}
}
pthread_exit(0);
}
[ 本帖最后由 wuxiangzhi 于 2007-10-31 14:31 编辑 ] |
|