学习进程控制与进程通信
用命名管道来实现两个进程间的通信:
进程A通过管道发送一个“list”字符串给进程B;
进程B收到进程A发送过来的“list”命令后,读取当前目录下的所有普通文件把文件名显示到屏幕;
进程A通过管道发送一个“end”字符串给进程B;
进程B收到进程A发送过来的“end”命令后,结束自己的运行。
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<limits.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<ctype.h>
#define SERVER_FIFO_NAME "/opt/chengxs/temp/fifo/serv_fifo" /*服务专用的fifo*/
#define CLIENT_FIFO_NAME "/opt/chengxs/temp/fifo/client_%d_fifo" /*客户专用的fifo*/
struct data_to_pass
{
pid_t client_pid;
char text_data[256-1];
};
客户端:
/*
*客户程序
*/
#include"cliserv.h"
int main()
{
int server_fifo_fd,client_fifo_fd;
struct data_to_pass my_request;
int times_to_send;
char client_fifo_name[256];
pid_t mypid;
/*打开服务管道*/
server_fifo_fd = open(SERVER_FIFO_NAME,O_WRONLY);
if(server_fifo_fd == -1)
{
perror("Sorry,no server");
exit(1);
}
/*创建以进程ID命名的客户接收管道*/
mypid = getpid();
sprintf(client_fifo_name,CLIENT_FIFO_NAME,mypid);
if(mkfifo(client_fifo_name,0777) == -1)
{
perror(client_fifo_name);
exit(2);
}
/*向服务进程连续发送和接收五次数据*/
for(times_to_send=0;times_to_send<5;times_to_send++)
{
sprintf(my_request.text_data,"Hello from %d,%d",mypid,times_to_send);
my_request.client_pid = mypid;
/*向服务进程发出请求*/
printf("%d send: %s,",mypid,my_request.text_data);
write(server_fifo_fd,&my_request,sizeof(my_request));
/*从服务进程接收回答,打开客户有名管道*/
client_fifo_fd = open(client_fifo_name,O_RDONLY);
if(client_fifo_fd!=-1)
{
if(read(client_fifo_fd,&my_request,sizeof(my_request))>0)
{
printf("%d received: %s/n",mypid,my_request.text_data);
}
close(client_fifo_fd);
}
}
close(server_fifo_fd);
unlink(client_fifo_fd);
exit(0);
}
服务端:
/*
*服务程序
*/
#include"cliserv.h"
int main()
{
int server_fifo_fd,client_fifo_fd;
struct data_to_pass my_data;
int nbytes;
char client_fifo_name[256];
char * tmp_char_ptr;
/*创建并打开服务FIFO*/
mkfifo(SERVER_FIFO_NAME,0777);
server_fifo_fd = open(SERVER_FIFO_NAME,O_RDONLY);
if(server_fifo_fd == -1)
{
perror("Server info failed!");
exit(1);
}
/*客户请求排队*/
sleep(10);
do
{
/*接收来自客户的请求*/
nbytes = read(server_fifo_fd,&my_data,sizeof(my_data));
if(nbytes>0)
{
/*处理客户请求*/
tmp_char_ptr = my_data.text_data;
while(*tmp_char_ptr)
{
*tmp_char_ptr = toupper(*tmp_char_ptr);
tmp_char_ptr++;
}
/*返回处理过的数据*/
sprintf(client_fifo_name,CLIENT_FIFO_NAME,my_data.client_pid);
client_fifo_fd = open(client_fifo_name,O_WRONLY);
if(client_fifo_fd != -1)
{
write(client_fifo_fd,&my_data,sizeof(my_data));
close(client_fifo_fd);
}
}
}while(nbytes>0);
close(server_fifo_fd);
unlink(SERVER_FIFO_NAME);
return 0;
}