linux下两个程序的简单单向通信
client1将输出重定向到文件chat.dat, client2将输入重定向为从文件chat.dat中输入。
/*************************************************************************
> File Name: client1.c
> Author: qinf
> Mail:
> Created Time: Tue 25 Mar 2014 04:57:12 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open(argv[1], O_WRONLY);
if (-1 == fd)
{
perror("failed to open\n");
exit(-1);
}
char buf[128] = "";
char buf2[128] = "";
int cnt;
dup2(fd, 1);
while (1) {
cnt = read(0, buf, 128);
buf[cnt] = '\0';
sprintf(buf2, "client1: %s", buf);
write(1, buf2, strlen(buf2));
}
close(fd);
return 0;
}
/*************************************************************************
> File Name: client2.c
> Author: qinf
> Mail:
> Created Time: Tue 25 Mar 2014 04:56:55 PM CST
************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open(argv[1], O_RDONLY);
char buf[128] = "";
// char buf2[128] = "";
if (-1 == fd)
{
perror("failed to open chat file\n");
exit(-1);
}
dup2(fd, 0);
close(fd);
while (1) {
int cnt = read(0, buf, 128);
buf[cnt] = '\0';
if (strncmp(buf, "client", 6) == 0)
{
puts(buf);
}
}
return 0;
}