两个程序在Makefile

时间:2016-02-09 04:58:01

标签: c linux makefile named-pipes

我是linux的新手,我尝试制作服务器(读者)和客户端(作家);
所以客户可以发送"嗨"到具有命名管道的服务器。

我已经写了两个程序。当我在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

以上是我到目前为止编写的代码。这是一个来自其他问题教程和视频的简单代码。

1 个答案:

答案 0 :(得分:2)

当你需要两个程序时,你正在构建一个程序。

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__ */

生成文件

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

您将获得两个可执行文件,客户端和服务器。在另一个xterm中运行它们。