急,求助,linux下的简单编程实现!

来源:百度知道 编辑:UC知道 时间:2024/09/21 12:33:32
编程实现
 进程间通信(通信方式可以是消息队列等)
进程A发送命令字符串到进程B;
进程B根据收到的字符串的不同执行不同的操作(很简单的操作)

下面这段程序是两个进程通信的例子。效果是,先是进程1(pid1)给进程2(pid2)发送“Send pid2 message:Hello pid2” 在进程2接收并显示出来,然后进程2给进程1发送“send message:Hello pid1”,进程1接收后并显示出来。如此循环5一结束。希望对你有用。
#include "stdio.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "errno.h"
#include "string.h"
#include "signal.h"
int main()
{
int s[2];
int state;
int pid1,pid2;
char buf1[64];
char buf2[64];
char *msg1="Hello pid2";
char *msg2="Hello pid1";
state=socketpair(AF_LOCAL,SOCK_STREAM,0,s);
if(state)
perror("Error");
printf("Connection start...\n");
pid1=fork();
if(0==pid1)
{
close(s[1]);
while(1)
{
printf("Send pid2 message:%s\n",msg1);
write(s[0],msg1,strlen(msg1));