資源簡(jiǎn)介
/**************************************************************************/
//本程序是利用LINUX FIFO命名管道技術(shù)實(shí)現(xiàn)雙向聊天的C語(yǔ)言源代碼。
//優(yōu)點(diǎn):代碼簡(jiǎn)潔明了。
//其中:
//chat.c: 聊天源代碼。
//makefile: 利用宏定義,把一個(gè)源碼生成兩個(gè)不同的可執(zhí)行程序。
//
//使用:
//make clean 清除上次編譯生成的結(jié)果文件。
//make 重新編譯生成兩個(gè)可執(zhí)行程序。./a_chat和./b_chat的執(zhí)行順序沒(méi)有先后。
//作者:david.q@sz 2012-8-11 2263537@qq.com
/**************************************************************************/

代碼片段和文件信息
/**************************************************************************/
//本程序是利用LINUX?FIFO命名管道技術(shù)實(shí)現(xiàn)雙向聊天的C語(yǔ)言源代碼。
//優(yōu)點(diǎn):代碼簡(jiǎn)潔明了。
//其中:
//chat.c:?聊天源代碼。
//makefile:?利用宏定義,把一個(gè)源碼生成兩個(gè)不同的可執(zhí)行程序。
//
//使用:
//make?clean?清除上次編譯生成的結(jié)果文件。
//make?重新編譯生成兩個(gè)可執(zhí)行程序。./a_chat和./b_chat的執(zhí)行順序沒(méi)有先后。
//作者:david.q@sz?2012-8-11?2263537@qq.com
/**************************************************************************/
#include?
#include?
#include?
#include?
#include?
#include?
#include?
int?main(?int?argc?char?*argv[]?)
{
#ifdef?A
char?me[]?=?“a“;
char?you[]?=?“b“;
#else
char?me[]?=?“b“;
char?you[]?=?“a“;
#endif
char?buf[100];
char?get[100];
printf(?“Hello?%s!\n“?me?); //print?welcome?message
pid_t?pid;
pid?=?fork();
if?(?pid?==?0?) //child?process
{
int?fifo_f;
#ifdef?A
char?fifo[]?=?“/tmp/b2a“;
#else
char?fifo[]?=?“/tmp/a2b“;
#endif
mkfifo(?fifo?0666?); //creat?fifo?if?exist?or?not
if?(?errno?==?EEXIST?)
{
fifo_f?=?open(?fifo?O_RDONLY?); //wait?&?open?fifo
}
//read
while?(?1?)
{
bzero(?get?sizeof(get)); //set?buf?to?‘\0‘?before?read?buf
read(?fifo_f?get?sizeof(get)?); //read?buf?from?another?side
if?(?strlen(get)?)
{
printf(?“\r%s:?%s“?you?get?);
printf(?“%s:?“?me?);
fflush(stdout); //print?buf?to?screen
usleep(100);
}
}
}
else //parent?process
{
int?fifo_f;
#ifdef?A
char?fifo[]?=?“/tmp/a2b“;
#else
char?fifo[]?=?“/tmp/b2a“;
#endif
mkfifo(?fifo?0666?); //creat?fifo?if?exist?or?not
if?(?errno?==?EEXIST?)
{
fifo_f?=?open(?fifo?O_WRONLY?); //wait?&?open?fifo
}
//write
while?(?1?)
{
printf(?“%s:?“?me?);
fflush(stdout); //print?to?screen
bzero(?buf?sizeof(buf)?); //set?buf?to?‘\0‘?before?get?from?stdin
fgets(?buf?sizeof(buf)?stdin?); //get?buf?from?stdin
write(?fifo_f?buf?sizeof(buf)?); //send?buf?to?anoterh?side
usleep(100);
}
}
return?0;
}
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件???????2187??2012-08-12?16:57??chat.c
?????文件????????179??2012-08-12?12:00??Makefile
-----------?---------??----------?-----??----
?????????????????2366????????????????????2
評(píng)論
共有 條評(píng)論