我创建了这个应用程序,其中两个进程进行通信。一切都很好,但我希望当用户按下 esc 时,进程会自动结束。s*其次,它只从用户那里得到一条线。一次在一个过程中*。在进入第二行之前,我们还必须在另一个进程中添加一行。这是进程 1 的代码(我称为服务器)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>
extern int errno;
#define FIFO1 "/tmp/fifo.1"
#define FIFO3 "/tmp/fifo.3"
#define PERMS 0666
#define MESSAGE1 "client Says:"
main()
{
char buff[BUFSIZ];
int readfd, writefd;
int n, size;
if ((mknod (FIFO1, S_IFIFO | PERMS, 0) < 0) && (errno != EEXIST)) {
perror ("mknod FIFO1");
exit(1);
}
if (mkfifo(FIFO3, PERMS) < 0 && (errno != EEXIST)) {
unlink (FIFO1);
perror("mknod FIFO3");
exit(1);
}
if ((readfd = open(FIFO1, 0)) < 0) {
perror ("open FIFO1");
exit(1);
}
if ((writefd = open(FIFO3, 1)) < 0) {
perror ("open FIFO3");
exit(1);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
loop:
while(1)
{
if ((n = read(readfd, buff, 100)) < 0) {
perror ("server read"); exit (1);
}
write(1,MESSAGE1,strlen(MESSAGE1));
if (write(1, buff, n) != n) {
perror ("client write2"); exit(1);
}
/////////////////////////////////////////////////////////////////////////////////////////////
while(1)
{
printf("server says:");
//strcpy(buff,"I say:");
fgets(buff,100,stdin);
n=strlen(buff) + 1;
if (write(writefd, buff,n) < n) {
perror("server write1"); exit (1);
}
goto loop;
}
}//end of first for
close (readfd); close (writefd);
}
第二个过程(我叫客户)
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>
extern int errno;
#define FIFO1 "/tmp/fifo.1"
#define FIFO3 "/tmp/fifo.3"
#define PERMS 0666
#define MESSAGE1 "server Says:"
main()
{
char buff[BUFSIZ];
char buf[]="logout";
int readfd, writefd, n, size;
if ((writefd = open(FIFO1, 1)) < 0) {
perror ("client open FIFO1"); exit(1);
}
if ((readfd = open(FIFO3, 0)) < 0) {
perror ("client open FIFO3"); exit(1);
}
///////////////////////////////////////////////////////////
loop:
while(1)
{
printf("client says:");
fgets(buff,100,stdin);
n=strlen(buff) + 1;
if (write(writefd, buff,n) < n)
{
perror("server write1"); exit (1);
}
////////////////////////////////////////////
while(1)
{
if ((n = read(readfd, buff, 100)) < 0)
{
perror ("client read"); exit(1);
}
write(1,MESSAGE1,strlen(MESSAGE1));
if (write(1, buff, n) != n)
{
perror ("client write2"); exit(1);
}
goto loop;
}
}//end of first for
close(readfd); close(writefd);
/* Remove FIFOs now that we are done using them */
if (unlink (FIFO1) < 0) {
perror("client unlink FIFO1");
exit(1);
}
if (unlink (FIFO3) < 0) {
perror("client unlink FIFO3");
exit(1);
}
exit(0);
}