I am new at linux and I try to make a server(reader) and a client(writer);
so the client can send "Hi" to server with named pipes.
I have write the both programs. How can I make them communicate with the named pipe when I build them in a Makefile?
//server programm:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "fun.h"
#define MAX_BUF 1024
int main()
{
int pid,fd,status;
char * myfifo = "/home/pipe";
char buf[MAX_BUF];
pid=fork();
wait(&status);
if (pid<0){
exit(1);
}
if (pid==0){
mkfifo(myfifo, 0666);
fd = open(myfifo, O_RDONLY);
main1();
read(fd, buf, MAX_BUF);
printf("%s\n", buf);
}
else{
printf("i am the father and i wait my child\n");
}
close(fd);
return 0;
}
//client program:
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "fun.h"
int main1()
{
int fd;
char * myfifo = "/home/pipe";
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
unlink(myfifo);
return 0;
}
//fun.h:
int main1()
//Makefile:
all: client.o server.o
gcc client.o server.o -o all
client.o: client.c
gcc -c client.c
server.o: server.c
gcc -c server.c
clean:
rm server.o client.o
Above is the code I have write so far. It sa simple code from other questions tutorials and videos.
You are building a single program while you need two.
server.c
#include "fun.h"
// system includes
int main(int argc, char *argv[])
{
// code you put in your main()
}
client.c
#include "fun.h"
// system includes
int main(int argc, char *argv[])
{
// code you put in your main1()
}
fun.h
#ifndef __FUN_H__
#define __FUN_H__
#define MY_FIFO "/home/pipe"
#endif /* __FUN_H__ */
makefile
INSTALL_PATH=/home/me/mybin/
all: server client
install: all
cp server client all.sh $(INSTALL_PATH)
uninstall:
rm -f $(INSTALL_PATH)server $(INSTALL_PATH)client $(INSTALL_PATH)all.sh
server: server.o
gcc server.o -o server
client: client.o
gcc client.o -o client
server.o: server.c fun.h
gcc -c server.c
client.o: client.c fun.h
gcc -c client.c
.PHONY: all install uninstall
You will get two executables, client and server. Run each of them in a different xterm.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.