【问题标题】:two programs one named pipe in a MakefileMakefile 中的两个程序一个命名管道
【发布时间】:2016-02-09 04:58:00
【问题描述】:

我是 linux 新手,我尝试制作服务器(读取器)和客户端(写入器);
因此客户端可以使用命名管道向服务器发送“Hi”。

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

以上是我目前写的代码。这是其他问题教程和视频中的简单代码。

【问题讨论】:

  • 首先让您的客户端/服务器在 cmd 行上工作。然后制作一个shell脚本来管理进程,即创建命名管道,在后台运行服务器,运行客户端并通过命名管道发送数据,然后关闭/清理。然后,您可以寻找如何将对 shell 脚本的调用嵌入到 makefile 中。祝你好运。
  • 谢谢!!我相信这就是我要找的!

标签: c linux makefile named-pipes


【解决方案1】:

您正在构建一个程序,而您需要两个程序。

服务器.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 中运行它们。

【讨论】:

  • 首先谢谢你的回答!!你是对的!当我需要两个程序时,我编写了一个程序。但我希望它们在同一个终端中运行。我希望服务器在后台运行,客户端向他发送消息。我用一个shell脚本管理它。现在我要做的是在 Makefile 中创建 shell 脚本并运行它。
  • @ClockWork “在 Makefile 中创建 shell 脚本并运行它”是什么意思?我不清楚。
  • @ClockWork "all" 对于程序来说似乎是个坏名字,因为它与 makefile 中传统的 "all" 目标混淆了,而且大多数人都习惯于使用 "make all" 命令进行构建。您应该将其命名为“all.sh”、“all.ksh”或“all.bash”,具体取决于您要使用的 shell。你不需要使用make来生成它,不需要编译。随便写,也许你可以在你的make文件中添加一个“安装”目标,以便在生产环境中复制它。
猜你喜欢
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 2012-03-10
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
相关资源
最近更新 更多